如何使用groovy解析json [英] how to parse json using groovy
问题描述
我想解析即将到来的JSON数据:
{
212315952136472:{
id:212315952136472,
name:Ready,
picture:http://profile.ak.fbcdn.net/hprofile-ak-snc4/ 195762_212315952136472_4343686_s.jpg,
link:http://www.hityashit.com/movie/ready,
likes:5,
category:电影 ,
description:查看http://www.hityashit.com/movie/ready上的Ready的评论
}
}
$ c $
JSONElement userJson = JSON.parse(jsonResponse)
userJson.data.each {
Urls = it.link
}
但我无法获得任何分配给 Urls
的任何内容。任何建议?
解决方案该响应是一个Map,带有一个键为'212315952136472'的单个元素。地图中没有数据键。如果你想遍历所有的条目,使用这样的东西:
JSONObject userJson = JSON.parse(jsonResponse)
userJson.each {id,data - > println data.link}
如果您知道这是一个单元素Map,那么您可以直接访问 link
:
def data = userJson.values()。iterator() .next()
String link = data.link
如果你知道id例如,如果您使用它来发出请求),那么您可以更简洁地访问该值:
String id ='212315952136472'
...
String link = userJson [id] .link
I want to parse JSON data which is coming in like:
{
"212315952136472": {
"id": "212315952136472",
"name": "Ready",
"picture": "http://profile.ak.fbcdn.net/hprofile-ak-snc4/195762_212315952136472_4343686_s.jpg",
"link": "http://www.hityashit.com/movie/ready",
"likes": 5,
"category": "Movie",
"description": "Check out the reviews of Ready on http://www.hityashit.com/movie/ready"
}
}
The code I am using is:
JSONElement userJson = JSON.parse(jsonResponse)
userJson.data.each {
Urls = it.link
}
But I am not able to get anything assigned to Urls
. Any suggestions?
解决方案 That response is a Map, with a single element with key '212315952136472'. There's no 'data' key in the Map. If you want to loop through all entries, use something like this:
JSONObject userJson = JSON.parse(jsonResponse)
userJson.each { id, data -> println data.link }
If you know it's a single-element Map then you can directly access the link
:
def data = userJson.values().iterator().next()
String link = data.link
And if you knew the id (e.g. if you used it to make the request) then you can access the value more concisely:
String id = '212315952136472'
...
String link = userJson[id].link
这篇关于如何使用groovy解析json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!