Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to parse json using groovy

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?

like image 577
Nikhil Sharma Avatar asked Jul 14 '11 03:07

Nikhil Sharma


People also ask

What is Groovy JSON JsonSlurper?

JsonSlurper. JsonSlurper is a class that parses JSON text or reader content into Groovy data structures (objects) such as maps, lists and primitive types like Integer , Double , Boolean and String .

How do I iterate through a JSON array in Groovy?

You then loop through the array for (int i = 0; i < array. length(); i++) and retrieve each JSON object by calling array. getJSONObject(i); which returns JSONObject . From there, get the respective attribute value, e.g. long uid = json.

How do I create a JSON object in Groovy?

Groovy 1.8 introduced json package for parsing and building JSON data. JsonSlurper is used for parsing JSON and JsonBuilder is used for creating JSON in Groovy. For more details visit the API here and a good article here.


2 Answers

Have you tried using 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" 
like image 108
Dónal Avatar answered Oct 06 '22 08:10

Dónal


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 
like image 28
Burt Beckwith Avatar answered Oct 06 '22 09:10

Burt Beckwith