rkh
rkh

Reputation: 863

Sorting a json string by item value in groovy

I have the following code chunk:

def response =  '[{"id": "121","startTime": "2013-11-10T20:48:54Z", "reqId": 123456, "endTime": null, "numFiles"     :null}, 
{"id": "123","startTime": "2013-11-29T21:45:00Z","reqId": 123458,"endTime": "2013-11-30T21:45:00Z", "numFiles"     :null }, 
{"id": "121","startTime": "2013-11-8T20:48:54Z", "reqId": 123111, "endTime": null, "numFiles" :null}]'

 def sortedResponse = response.sort { a,b -> b.reqId <=> a.reqId}

def reqRespAPI = new JsonSlurper().parseText(sortedResponse )

def id = reqRespAPI.id
def stTime = reqRespAPI.startTime
def eTime = reqRespAPI.endTime
def rqId = reqRespAPI.reqId
def numRec = reqRespAPI.numFiles

...some other stuff here....

I am trying to sort by reqId (rqId) descending. Do I have to use a for loop? The current sortedResponse is throwing an exception:

groovy.lang.MissingMethodException: No signature of method: java.lang.String.sort() is applicable for argument types: (...Controller$_closure2_closure8) values: [....Controller$_closure2_closure8@5976ac5b]

I have also tried sort (new OrderBy(...)) but that also did not work...

Any help would be appreciated.

Upvotes: 3

Views: 8401

Answers (1)

billjamesdev
billjamesdev

Reputation: 14642

The issue seems to be that you're trying to sort the response String, rather than the collection of JSONObjects.

Try this?

def reqRespJSON = new JsonSlurper().parseText( response )
def sortedJSON = reqRespJSON.sort { a,b -> b.reqId <=> a.reqId}


def id = sortedJSON[0].id

Note that the sortedJSON is an List of Maps, so you have to specify which one you want the id from (using [0]).

Upvotes: 6

Related Questions