Grails render collection as a single json object

For example, I have the following domain class

User{ String name } 

I also have 2 objects of this class

 new User(name: "John").save() new User(name: "Alex").save() 

What the โ€œlistโ€ action in UserController should look like to represent User.list () in JSON format, such as

 {1: "John", 2: "Alex"} 

Let me be more precise. I want something like this:

 UserController{ def list = { render(contentType: "text/json") { User.list().each {user-> user.id = user.name } } } 

But, unfortunately, this does not work.

+4
source share
4 answers

I could not find a solution using the JSONBuilder API. Because of this, I made my decision using org.codehaus.jackson.

 response.setContentType("text/json") JsonGenerator g = jsonFactory.createJsonGenerator(response.getOutputStream()) g.writeStartObject() for (user in users) { g.writeStringField(user.id.toString(), user.name) } g.writeEndObject() g.close() 
+2
source

Try the array structure,

 def list = { render(contentType: "text/json") { results = array { User.list().each {user-> result "${user.id}" : "${user.name}" } } } } 
+2
source

When I want to code something like JSON in grails, I put everything on the cards:

 render ['1':john.name, '2':alex.name] as JSON 
+1
source

Beginning with @aldrin's answer, a fix is โ€‹โ€‹required to render json GRAILS3 since the array directive no longer works (and is the more correct "application" instead of "text"), so there should be a solution

 def list = { def ulist = User.list() render(contentType: "application/json") { results(ulist) { user -> userid user.id username user.name } } } 
0
source

Source: https://habr.com/ru/post/1416155/


All Articles