如何使用groovy解析json

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6688090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:55:39  来源:igfitidea点击:

how to parse json using groovy

jsongrailsgroovy

提问by Nikhil Sharma

I want to parse JSON data which is coming in like:

我想解析传入的 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": "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?

但是我无法将任何分配给Urls. 有什么建议?

回答by Dónal

Have you tried using JsonSlurper?

您是否尝试过使用JsonSlurper

Example usage:

用法示例:

def slurper = new JsonSlurper()
def result = slurper.parseText('{"person":{"name":"Guillaume","age":33,"pets":["dog","cat"]}}')

assert result.person.name == "Guillaume"
assert result.person.age == 33
assert result.person.pets.size() == 2
assert result.person.pets[0] == "dog"
assert result.person.pets[1] == "cat"

回答by Burt Beckwith

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:

该响应是一个 Map,带有一个键为“212315952136472”的元素。地图中没有“数据”键。如果要遍历所有条目,请使用以下内容:

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:

如果你知道它是一个单元素 Map 那么你可以直接访问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:

如果您知道 id(例如,如果您使用它来发出请求),那么您可以更简洁地访问该值:

String id = '212315952136472'
...
String link = userJson[id].link

回答by Andrii Abramov

You can map JSON to specific class in Groovy using asoperator:

您可以使用as运算符将 JSON 映射到 Groovy 中的特定类:

import groovy.json.JsonSlurper

String json = '''
{
  "name": "John",  
  "age": 20
}
'''

def person = new JsonSlurper().parseText(json) as Person 

with(person) {
    assert name == 'John'
    assert age == 20
}