how to parse json using groovy

Nikhil Sharma picture Nikhil Sharma · Jul 14, 2011 · Viewed 99.9k times · Source

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?

Answer

Dónal picture Dónal · Jul 14, 2011

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"