使用 Groovy 从 JSON 响应中提取第一个节点值

Extract first node value from JSON response using Groovy

我正在尝试从我的 JSON 响应中获取第一个节点值(ResourceItemID,即 2290)。 我的回复看起来像:

    {
   "Success": true,
   "TotalRecords": 41,
   "RoomSearchResult":    [
            {
         "ResourceItemID": 2290,
         "Name": "Room 23 (L02)",
         "LocationId": 7,
         "GroupID": 518,
         "FloorID": 2,
         "DefaultCapacity": 4,
         "CanBeBooked": true
      },
{
         "ResourceItemID": 2063,
         "Name": "Room 15 (L10)",
         "LocationId": 7,
         "GroupID": 518,
         "FloorID": 10,
         "DefaultCapacity": 8,
         "CanBeBooked": true
      }
   ],
   "Error":    {
      "ErrorCode": 0,
      "ErrorDescription": ""
   }
}

到目前为止我尝试了什么:

import groovy.json.JsonSlurper
def parsed = new JsonSlurper().parseText(json).find().value.RoomSearchResult.ResourceItemID

您首先需要导航节点以找到您要从中提取值的特定节点类型,而不是先获取值。向下导航到 ResourceItemID,然后获取 value 将 return 所有 ResourceItemID 的值组成的数组:[2290,2063]。 您可以获取数组的第一项,也可以根据值本身进行查找。 下面的代码将打印示例结果:

[2290, 2063] 2290 2290

def parsed = new JsonSlurper().parseText(json).RoomSearchResult.ResourceItemID.value
println parsed
def result = parsed.find{ value -> value == 2290}
println result
result = parsed[0]
println result

如果你只想要第一个节点值那么你不需要手动遍历整个JSON,你可以将它解析为集合并从中获取第一个节点。

import groovy.json.JsonSlurper


String jsonString = """
  {
   "Success": true,
   "TotalRecords": 41,
   "RoomSearchResult":    [
            {
         "ResourceItemID": 2290,
         "Name": "Room 23 (L02)",
         "LocationId": 7,
         "GroupID": 518,
         "FloorID": 2,
         "DefaultCapacity": 4,
         "CanBeBooked": true
      },
      {
         "ResourceItemID": 2063,
         "Name": "Room 15 (L10)",
         "LocationId": 7,
         "GroupID": 518,
         "FloorID": 10,
         "DefaultCapacity": 8,
         "CanBeBooked": true
      }
   ],
   "Error":    {
      "ErrorCode": 0,
      "ErrorDescription": ""
   }
}
"""

JsonSlurper jsonSlurper = new JsonSlurper()

/**
* 'jsonString' is the input json you have shown
* parse it and store it in collection
*/
Map convertedJSONMap  = jsonSlurper.parseText(jsonString)

//If you have the nodes then fetch the first one only
if(convertedJSONMap."RoomSearchResult"){

    println "ResourceItemID : " + convertedJSONMap."RoomSearchResult"[0]."ResourceItemID"
}   

输出:

ResourceItemID : 2290