用Groovy按项值对JSON字符串进行排序。

3
我有以下代码块:
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....

我正在尝试按reqId(rqId)降序排序。我是否必须使用for循环?当前的sortedResponse抛出了一个异常:
groovy.lang.MissingMethodException: No signature of method: java.lang.String.sort() is applicable for argument types: (...Controller$_closure2_closure8) values: [....Controller$_closure2_closure8@5976ac5b]
我还尝试过sort(new OrderBy(...)),但那也不起作用...
任何帮助都将不胜感激。
1个回答

6
问题似乎在于你尝试对响应字符串进行排序,而不是JSON对象的集合。
尝试这个?
def reqRespJSON = new JsonSlurper().parseText( response )
def sortedJSON = reqRespJSON.sort { a,b -> b.reqId <=> a.reqId}


def id = sortedJSON[0].id

请注意,sortedJSON是一个Map列表,因此您需要指定您想要id的哪个Map(使用[0])。

1
这是一个 Map 列表,不是 JSONObjects 数组 ;-) - tim_yates
谢谢。问题已解决。请根据 @tim_yates 的指示更新您的回复。 - rkh
请问有人能告诉我为什么在 LazyMap 的文档中没有提到 sort,这是 JSON 返回类型之一? - Leponzo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接