user1245222
user1245222

Reputation:

Grails json using list

My Domain Class is declared as I m using Grails 1.3.7

StudentReport{
  String username
  String studentName
}

 def sp = StudentReport.createCriteria()



def studentReportList = sp.list {

            projections {
               property 'username'
                property 'studentName'
            }
            firstResult 0
            maxResults 20
            order("id", "asc")
        } 
render studentReportList as JSON

My expected result is

[
{"username":"13B06","student_name":"JOHN SAMUEL"},
{"username":"13B07","student_name":"KATHIRESAN.K"},
{"username":"13B08","student_name":"KATHIRESAN.K"},
{"username":"13B11","student_name":"MALINI.S"}
]

But what i get is

[
   ["13B06","JOHN SAMUEL"],
   ["13B07","KATHIRESAN.K"],
   ["13B08","KATHIRESAN.K"],
   ["13B11","MALINI.S"]
]

I need property name along with curly braces. Could any one help me out. I have tried without using projections in my controller, then i was getting the exact result but if i try using projections, then i held up in getting the same results.

Upvotes: 0

Views: 511

Answers (1)

Ian Roberts
Ian Roberts

Reputation: 122364

[ {"13B06","JOHN SAMUEL"},{"13B07","KATHIRESAN.K"},{"13B08","KATHIRESAN.K"},{"13B11","MALINI.S"} ]

is not valid JSON. The output you are currently getting is correct, because studentReportList is a List of Lists, so the JSON must be an array of arrays. If you want braces then the inner elements would need to be JSON objects rather than arrays. To generate

[
  {"username":"13B06","student_name":"JOHN SAMUEL"},
  ...
]

you could add a suitable result transformer to your criteria and use the two-argument form of the property projection method to assign the right aliases:

def studentReportList = sp.list{
        projections {
           property 'username', 'username'
            property 'studentName', 'student_name'
        }
        firstResult 0
        maxResults 20
        order("id", "asc")
        resultTransformer AliasToEntityMapResultTransformer.INSTANCE
    }

(along with the appropriate import) to make the criteria return a List of Maps rather than a List of Lists.

Upvotes: 2

Related Questions