Hi all, my name is Hubert A. Klein Ikkink. Not a very common name, right? To make things easier I just picked the first letters of my firstname and surname and came up with haki. So there you have it, now I am also known as Mr. Haki or mrhaki for short. You can read more blog postings at www.mrhaki.com. I am a passionate Groovy and Java developer based in Tilburg, The Netherlands. My goal is to write clean, elegant, user-centered and high quality software. You can find me on Google+ and Twitter. Hubert is a DZone MVB and is not an employee of DZone and has posted 173 posts at DZone. You can read more from them at their website. View Full User Profile

Groovy Goodness: Relax... Groovy Will Parse Your Wicked JSON

08.09.2014
| 6757 views |
  • submit to reddit
Since Groovy 2.3 the JSON parser has improved and is really a performant parser for JSON payload. JSON must be formatted in a strict way, for example all keys must be enclosed in double quotes. But what if we have JSON which not applies to the strict specification? For example a configuration file written in JSON and we want to add comments to this file. Or use single quotes for keys, or just leave all the quotes out. We can now specify the type JsonParseType.LAX for our JSON parser and we can now parse JSON which doesn't apply to the strict specification.
import groovy.json.*
import static groovy.json.JsonParserType.LAX as RELAX

def jsonText = '''
{
    message: {
        
        /* Set header of message */
        header: {
            "from": 'mrhaki',
            'to': ["Groovy Users", "Java Users"]
        }
        
        # Include a little body for the message.
        'body': "Check out Groovy's gr8 JSON support."
    }
}       
'''

def json = new JsonSlurper().setType(RELAX).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."

Code written with Groovy 2.3.6.

Published at DZone with permission of Hubert Klein Ikkink, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)