Wednesday, April 27, 2011

Groovy Goodness: Parse JSON with JsonSlurper

With Groovy 1.8 we can parse JSON text with the JsonSlurper class. We only have to feed the text to the parseText() method and we can the values are mapped to Maps and Lists. And getting the content then is very easy:

import groovy.json.*

def jsonText = '''
    "message": {
        "header": {
            "from": "mrhaki",
            "to": ["Groovy Users", "Java Users"]
        "body": "Check out Groovy's gr8 JSON support."

def json = new JsonSlurper().parseText(jsonText)

def header = json.message.header
assert header.from == 'mrhaki'
assert header.to[0] == 'Groovy Users'
assert header.to[1] == 'Java Users'
assert json.message.body == "Check out Groovy's gr8 JSON support."


Anonymous said...

I am very happy that Groovy includes JSON handling, but I wonder why JsonSlurper's methods are not static. The class does not persist any state. I use it on the command-line with '-e' and typing "new" every time I use it is awkward.

Post a Comment