Groovy 2.3 Json Parser Improvements

Using notes from guillaume’s presentation @devoxx France https://speakerdeck.com/glaforge/groovy-in-2014-and-beyond-at-devoxx-france , i liked these improvements to be able to read framework configuration files using the new json parser. It is tricky if your json payload is not constructed with unquoted keys and quoted strings (but unquoted integers). so tried this sample:

// https://speakerdeck.com/glaforge/groovy-in-2014-and-beyond-at-devoxx-france
// JSONSlurper for config files using groovy 2.3.0

import groovy.json.*
import static groovy.json.JsonParserType.*
def parser = new  JsonSlurper().setType(LAX)
def conf  = parser.parseText '''
{
    // no quotes for keys, single quote for values but not integers
    environment:'production'
    server: 5
    name:'fred'
    age:21
}
'''

assert conf.environment=='production'
println "Number of servers:"+conf.server
println "Server age:"+conf.age

/*
Number of servers:5
Server age:21
*/

			

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s