我试图从我的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
答案 0 :(得分:2)
如果您只想要第一个节点值,那么您不需要手动遍历整个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
答案 1 :(得分:0)
首先需要导航节点以获取要从中提取值的特定节点类型,而不是值。向下导航到ResourceItemID
然后获取value
将返回所有ResourceItemID
s:[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