簡體   English   中英

在groovy中按項目值對json字符串進行排序

[英]Sorting a json string by item value in groovy

我有以下代碼塊:

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]

我也嘗試過排序(new OrderBy(...)),但是也沒有用...

任何幫助,將不勝感激。

問題似乎是您正在嘗試對響應String排序,而不是JSONObjects的集合。

嘗試這個?

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


def id = sortedJSON[0].id

請注意,sortedJSON是“地圖列表”,因此必須指定要使用其ID的ID(使用[0])。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM