Search

Dark theme | Light theme

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."