无法使用groovy访问JSON字段

时间:2017-09-28 16:30:30

标签: java json groovy

我正在尝试使用groovy从API响应中提取信息

我想查看存储在“res”键下的信息。

身体的某些方面。措施02:00:00:02:06:70.res

无法弄清楚必须在不抛出nullpointerexception的情况下访问此信息。

"body":[  {
     "_id":"70:ee:50:01:fe:96",
     "place":{
        "location":[
           -70.863189,
           42.273936
        ],
        "altitude":26.154942,
        "timezone":"America\/New_York"
     },
     "mark":12,
     "measures":{
        "02:00:00:02:06:70":{
           "res":{
              "1506611038":[
                 22,
                 66
              ]
           },
           "type":[
              "temperature",
              "humidity"
           ]
        },
        "06:00:00:01:97:28":{
           "wind_strength":15,
           "wind_angle":343,
           "gust_strength":29,
           "gust_angle":301,
           "wind_timeutc":1506611083
        },
        "70:ee:50:01:fe:96":{
           "res":{
              "1506611086":[
                 1007.4
              ]
           },
           "type":[
              "pressure"
           ]
        }
     },
     "modules":[
        "02:00:00:02:06:70",
        "06:00:00:01:97:28"
     ],
     "module_types":{
        "02:00:00:02:06:70":"NAModule1",
        "06:00:00:01:97:28":"NAModule2"
     }
  }






 ],
"status":"ok",
"time_exec":0.017483949661255,
"time_server":1506611446
 }

1 个答案:

答案 0 :(得分:0)

body是一个包含一个元素的数组,因此您必须执行body[0].measures.'02:00:00:02:06:70'.res,e。 G。像

new groovy.json.JsonSlurper().parseText('''{"body":[  {
     "_id":"70:ee:50:01:fe:96",
     "place":{
        "location":[
           -70.863189,
           42.273936
        ],
        "altitude":26.154942,
        "timezone":"America/New_York"
     },
     "mark":12,
     "measures":{
        "02:00:00:02:06:70":{
           "res":{
              "1506611038":[
                 22,
                 66
              ]
           },
           "type":[
              "temperature",
              "humidity"
           ]
        },
        "06:00:00:01:97:28":{
           "wind_strength":15,
           "wind_angle":343,
           "gust_strength":29,
           "gust_angle":301,
           "wind_timeutc":1506611083
        },
        "70:ee:50:01:fe:96":{
           "res":{
              "1506611086":[
                 1007.4
              ]
           },
           "type":[
              "pressure"
           ]
        }
     },
     "modules":[
        "02:00:00:02:06:70",
        "06:00:00:01:97:28"
     ],
     "module_types":{
        "02:00:00:02:06:70":"NAModule1",
        "06:00:00:01:97:28":"NAModule2"
     }
  }






 ],
"status":"ok",
"time_exec":0.017483949661255,
"time_server":1506611446
 }}''').body[0].measures.'02:00:00:02:06:70'.res