Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

DZone's Guide to

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

· Java Zone
Free Resource

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

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.

Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.

Topics:

Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}