Groovy

Groovy Json Example

In this article we will see how to manipulate JSON data in Groovy. JSON (JavaScript Object Notation) is the much preferred data format these days for the exchange of data between the interested parties (client and server), due to its light weight nature and ease of use.

Groovy has a built in support to work with JSON data – be it with the literal data or the the Java objects in memory. It offers a simple way to parse and build the data into JSON format.

This article will show the various situations in which you need to have a JSON format.
 
 
 

1. Environment

The examples shown below are executed in the Command Prompt / Shell. But they are guaranteed to work with any of the IDEs (like Eclipse, IntelliJ IDEA, Netbeans) through the respective plugins. The examples are executed with the Groovy Version Groovy Version: 2.4.3.

2. Important Classes

Since version 1.8, Groovy offers two classes viz JsonSlurper and JsonBuilder. These classes offer various methods to help us deal with the JSON data.

JsonSlurper is a parser which reads the input data and gets the JSON content backed up by a Java Collection (Map or List). By iterating the Collection we can get the required JSON data in the form of Domain Model class (POJO/POGO) to be used in further layers of the application. The term POJO stands for Plain Old Java Object and POGO stands for Plain Old Groovy Object. The JsonSlurper can read from various different inputs ranging from literal String, File, URL, Map etc.,

JsonBuilder class helps you to build the JSON data from your existing Domain Class (or POGO). Using the JSONBuilder object you can either get the JSON data in a ordinary String (which will be compressed and not so good for human reading), prettyPrint format (neatly formatted content for display which will be human readable), write the data into a file etc.,

In addition to these classes, we have an another useful Utiltity class called JsonOutput.

JSONOutput is a helper class facilitating the transformation of the JSON content from various source formats through its overloaded method toJson(). You can use the relevant method to get the JSON output from the underlying source which is passed as argument. It also offers a prettyPrint method for a human readable output.

For example, toJson(String string) produces the JSON representation for the String data passed, whereas toJson(Map map) returns the JSON representation for a Map that is passed as an argument.

We will use a mixture of all these in the below set of examples.

Please note that these classes belong to the package groovy.json and this package is NOT imported by default. We need to explicitly import the classes to be available in our groovy scripts.

3. JSON Examples

We will see a set of examples for different scenarios to work with JSON output. The source code and output are mostly self explanatory and hence will have a minimal explanation wherever required.

3.1. Producing JSON data from a literal String

Let us see a very simple example where we can produce the JSON data from a plain text (literal String) without actually generating an object. We will use JsonOutput class for this purpose.

JsonLiteral.groovy

package com.javacodegeeks.example.groovy.json;

import groovy.json.JsonOutput;

def jsonLiteral = ["name": "Raghavan", "id" : 1]

println "JSON Literal as String : " + jsonLiteral
println "JSON Literal as JSON : " + JsonOutput.toJson(jsonLiteral)
println "JSON Literal as JSON formatted : "
println JsonOutput.prettyPrint(JsonOutput.toJson(jsonLiteral))

The above script produces the following output.

JSON Literal as String : [name:Raghavan, id:1]
JSON Literal as JSON   : {"name":"Raghavan","id":1}
JSON Literal as JSON formatted : 
{
    "name": "Raghavan",
    "id": 1
}

3.2. Producing JSON data from a POGO

Let us see an example where we can generate the JSON output from a POGO (Plain Old Groovy Object).

JsonFromPOGO.groovy

package com.javacodegeeks.example.groovy.json;

import groovy.json.JsonOutput

class Person
{
    String name
    int age
    
    String toString()
    {
        "[Person] name : ${name}, age : ${age}"
    }
}
def person = new Person(name:'Raghavan',age:34)
println "Person Object : " + person
println "Person Object in JSON : " + JsonOutput.toJson(person)
println "JSON Pretty Print"
println "-----------------"
// prettyPrint requires a String and NOT an Object
println JsonOutput.prettyPrint(JsonOutput.toJson(person))
println ""

/* Let us work with a list of Person instances */
def json = JsonOutput.toJson([new Person(name : "Vignesh", age : 50),
            new Person(name : "Murugan", age: 45)])
println "JSON Object List : " + json
println "JSON Pretty Print "
println "------------------"
println JsonOutput.prettyPrint(json)

Please note that we have used two different toJson(..) methods above. Depending on the input argument passed (Object, List) the corresponding overloaded toJson() method will be invoked.

The above script produces the following output.

Person Object : [Person] name : Raghavan, age : 34
Person Object in JSON : {"age":34,"name":"Raghavan"}
JSON Pretty Print
-----------------
{
    "age": 34,
    "name": "Raghavan"
}

JSON Object List : [{"age":50,"name":"Vignesh"},{"age":45,"name":"Murugan"}]
JSON Pretty Print 
------------------
[
    {
        "age": 50,
        "name": "Vignesh"
    },
    {
        "age": 45,
        "name": "Murugan"
    }
]

3.3. Producing JSON data via JSONSlurper using literal String

JsonSlurper object gives us a JSON Object as a result of successful parsing of the input content passed to it. It has several overloaded methods parse() which accepts various different input sources right from literal String, File, URL, Map etc.,

We can use this JSON Object to fetch any properties of our interest by using the relevant hierarchy / relation.

We will see how we can generate the JSON output with the JsonSlurper instance below.

JsonSlurper1Basic.groovy

package com.javacodegeeks.example.groovy.json;

import groovy.json.JsonSlurper

def jsonSlurper = new JsonSlurper()
def inputText = '{"name" : "Groovy", "year": 2005}'

def jsonObject = jsonSlurper.parseText(inputText)
println "JSONObject generated out of JsonSlurper : " + jsonObject

println "jsonObject is of type : " +  jsonObject.getClass()
println "jsonObject is a Map ? " + (jsonObject instanceof Map)
assert jsonObject instanceof Map

println ""
println "Individual Attributes"
println "====================="
println "Object.name -> [" + jsonObject.name + "]"
println "Object.year -> [" + jsonObject.year + "]"

The above script produces the following output.

JSONObject generated out of JsonSlurper : [name:Groovy, year:2005]
jsonObject is of type : class groovy.json.internal.LazyMap
jsonObject is a Map ? true

Individual Attributes
=====================
Object.name -> [Groovy]
Object.year -> [2005]

In this example, we have used a literal text to be parsed by JsonSlurper instance and as a result we get a JSON Object. You can see that ‘jsonObject’ is of type ‘Map‘ (groovy.json.internal.LazyMap).

Later, we can retrieve the properties from a map using the usual dot notation (“.”) as in jsonObject.name and jsonObject.year respectively.

3.4. Producing JSON data via JSONSlurper using POGO Instance(s)

We can see how we can pass a literal String with a List object to be parsed by JsonSlurper and how we can manipulate the contents of a list.

JsonSlurper2List.groovy

package com.javacodegeeks.example.groovy.json;

import groovy.json.JsonSlurper

def jsonSlurper = new JsonSlurper()
def jsonObject = jsonSlurper.parseText('{ "vowels" : ["a", "e", "i", "o", "u"] }')

println "Json Object : " + jsonObject
println "Json Object Type : " + jsonObject.getClass()
println ""

println "Json Object - vowels : " + jsonObject.vowels
println "Json Object - vowels Type : " + jsonObject.vowels.getClass()
println "Json Object - vowels is a List ? " + (jsonObject.vowels instanceof List)
def listSize = jsonObject.vowels.size
println "Json Object - vowels Size : " + listSize
println "Json Object - vowels = first element : " + jsonObject.vowels.get(0)
println "Json Object - vowels = last  element : " + jsonObject.vowels.get(listSize-1)

The above script produces the following output.

Json Object : [vowels:[a, e, i, o, u]]
Json Object Type : class groovy.json.internal.LazyMap

Json Object - vowels : [a, e, i, o, u]
Json Object - vowels Type : class java.util.ArrayList
Json Object - vowels is a List ? true
Json Object - vowels Size : 5
Json Object - vowels = first element : a
Json Object - vowels = last  element : u

3.5. Producing JSON data via JSONSlurper and verify the data type of attributes

Below example code snippet shows that we can retrieve the data type of each of the members parsed out of JsonSlurper, which will be helpful for us to take a cautious decision while passing it further into the application.

JsonSlurper3DataTypes.groovy

package com.javacodegeeks.example.groovy.json;

import groovy.json.JsonSlurper

def jsonSlurper = new JsonSlurper()
def jsonObject = jsonSlurper.parseText '''
    {
        "name"        : "Raghavan",
        "age"         : 23,
        "temp"        : 98.4,
        "salary"      : 40000.25
    }
'''

println "JSON Object :  " + jsonObject
println "JSON Object class : " + jsonObject.getClass()
println ""
println "Individual Attributes and Data types "
println "======================================"
println "Datatype of name :  " + jsonObject.name.class
println "Datatype of age : " + jsonObject.age.class
println "Datatype of temp : " + jsonObject.temp.class
println "Datatype of salary : " + jsonObject.salary.class


In this example, we have used a different way of passing a literal text to JsonSlurper through a set of triple quotes (”’) for a multi-line string literal input.

The above script produces the following output, where you can see the data type of each of the members printed out in order. Please note that Groovy prefers BigDecimal, unlike Java which prefers a float or double for the floating point values.

JSON Object :  [age:23, name:Raghavan, salary:40000.25, temp:98.4]
JSON Object class : class groovy.json.internal.LazyMap

Individual Attributes and Data types 
======================================
Datatype of name :  class java.lang.String
Datatype of age : class java.lang.Integer
Datatype of temp : class java.math.BigDecimal
Datatype of salary : class java.math.BigDecimal

3.6. Parsing JSON data via JsonSlurper by reading an input file

We will see an example of how to read the json file from disk and work with the contents retrieved inside our groovy script.

We will read the contents of the file ’employee.json’ and also display the same with and without pretty print for your ease of use and verification.

JsonSlurper4File.groovy

package com.javacodegeeks.example.groovy.json;

import groovy.json.JsonSlurper
import groovy.json.JsonOutput

String inputFile = 'employee.json'
String fileContents = new File(inputFile).getText('UTF-8')

def jsonSlurper = new JsonSlurper()
def jsonObject = jsonSlurper.parseText(fileContents)

println "JSONObject : " + jsonObject
println ""
println "JSONObject type : " + jsonObject.getClass()
println " "
println "JSONObject pretty printed"
println "========================="
println JsonOutput.prettyPrint(fileContents)
println ""
println "Individual Attributes"
println "---------------------"
println "JSONObject employee firstName : " + jsonObject.employee.firstName
println "JSONObject employee age : " + jsonObject.employee.age
println "JSONObject employee project name : " + jsonObject.employee.project.name

The above script produces the following output. You can see the attributes of the object being retrieved from the JSON Object.

JSONObject : [employee:[age:35, country:India, department:Technology, firstName:Raghavan, lastName:Muthu, project:[manager:Mark, name:Payroll Automation]]]

JSONObject type : class groovy.json.internal.LazyMap

JSONObject pretty printed
=========================
{
    "employee": {
        "firstName": "Raghavan",
        "lastName": "Muthu",
        "age": 35,
        "country": "India",
        "department": "Technology",
        "project": {
            "name": "Payroll Automation",
            "manager": "Mark"
        }
    }
}

Individual Attributes
---------------------
JSONObject employee firstName : Raghavan
JSONObject employee age : 35
JSONObject employee project name : Payroll Automation

3.7. Creating JSON data via JSONBuilder from POGO

JsonBuilder class helps you to generate JSON from the Java objects. It is the reverse of JsonSlurper which reads and parses to get you the JSON Object.

We use JsonBuilder to generate a JSON specific data that can be either written to a file, for example configuration files for an application, or to a different URL source via a suitable java.io.Writer Implementation class.

The advantage and specialty of the JsonBuilder class is that you can very easily construct an object by specifying the members and their values in a literal String, without actually creating an instance of a separate POGO class. That is you can build your object at runtime. This way it is very helpful to create configuration classes which are JSON specific.

In the below example, the code snippet shows two parts – first generating a JSON object on the fly using the JsonBuilder and then parsing it into a Java object via JsonSlurper for manipulating its properties one by one.

JsonBuilder1Basic.groovy

package com.javacodegeeks.example.groovy.json;

import groovy.json.JsonBuilder
import groovy.json.JsonSlurper

// Part 1 - Create a JSON content on the fly using JsonBuilder 

def builder = new JsonBuilder()
builder.book {
    title 'Head First Java'
    publisher 'Orielly'
    author 'Kathy Sierra', 'Bert Bates'
    year '2005'
    currency 'USD'
    price 44.95
    format 'pdf', 'print'
}

println builder
println ""
println builder.toPrettyString()

/* Part 2 - Parse the Json Content into a JSON Object via JsonSlurper for further usage */

def jsonSlurper = new JsonSlurper()
def jsonBookObj = jsonSlurper.parseText(builder.toString())

println "JsonBook Object : " 
println jsonBookObj
println "JsonBook Object type : " + jsonBookObj.getClass()
println "JsonBook Object size : " + jsonBookObj.size()
println ""

def book = jsonBookObj.book
println "Book Instance : " 
println jsonBookObj.book
println "Book Instance Type : " + book.getClass()
println "Book Instance size : " + jsonBookObj.book.size()
println ""
println "Individual Attributes"
println "----------------------"
println "Title : " +  jsonBookObj.book.title + " || Type : " + book.title.getClass()
println "Author : " + book.author + " || Type : " + book.author.getClass() + " || Size : " + book.author.size
println "Price : " + book.price + " || Type : " + book.price.getClass()
println "Currency : " + book.currency +  " || Type : " + book.currency.getClass()
println "Format : " + book.format +  " || Type : " + book.format.getClass() + " || Size : " + book.format.size

The above script produces the following output.

{"book":{"title":"Head First Java","publisher":"Orielly","author":["Kathy Sierra","Bert Bates"],"year":"2005","currency":"USD","price":44.95,"format":["pdf","print"]}}

{
    "book": {
        "title": "Head First Java",
        "publisher": "Orielly",
        "author": [
            "Kathy Sierra",
            "Bert Bates"
        ],
        "year": "2005",
        "currency": "USD",
        "price": 44.95,
        "format": [
            "pdf",
            "print"
        ]
    }
}
JsonBook Object : 
[book:[author:[Kathy Sierra, Bert Bates], currency:USD, format:[pdf, print], price:44.95, publisher:Orielly, title:Head First Java, year:2005]]
JsonBook Object type : class groovy.json.internal.LazyMap
JsonBook Object size : 1

Book Instance : 
[author:[Kathy Sierra, Bert Bates], currency:USD, format:[pdf, print], price:44.95, publisher:Orielly, title:Head First Java, year:2005]
Book Instance Type : class groovy.json.internal.LazyMap
Book Instance size : 7

Individual Attributes
----------------------
Title : Head First Java || Type : class java.lang.String
Author : [Kathy Sierra, Bert Bates] || Type : class java.util.ArrayList || Size : 2
Price : 44.95 || Type : class java.math.BigDecimal
Currency : USD || Type : class java.lang.String
Format : [pdf, print] || Type : class java.util.ArrayList || Size : 2

3.8. Creating JSON data via JSONBuilder and Write to a File

In this example, we will see how we can generate the JSON data using the JsonBuilder and use its API method to write the JSON into a file in the disk.

This will be handy when we need to write our JSON specific configuration into a file which can later be read by a Container for serving our application to users.

In this example will write the contents into a file and subsequently we will read the file contents and display for our verification.

JsonBuilder2File.groovy

package com.javacodegeeks.example.groovy.json;

import groovy.json.JsonBuilder
import groovy.json.JsonOutput

def jsonBuilder = new JsonBuilder()

jsonBuilder.config
{
    env : "Prod"
    database {
        host "example.com"
        port 3306
        type "MySQL"
        user 'dbUser'
        pass 'dbPass'
        driver 'com.mysql.jdbc.Driver'
    }
    threadPool 10
    useBridge 'Y'
}

println "JSONBuilder Object : " + jsonBuilder
println ""
println "JSON Pretty Printed Config "
println "=========================="
println JsonOutput.prettyPrint(jsonBuilder.toString())
println ""

String outputFile = 'config.json'
def fileWriter = new FileWriter(outputFile)
jsonBuilder.writeTo(fileWriter)
fileWriter.flush() /* to push the data from  buffer to file */
println "Config details are written into the file '${outputFile}'"

println ""
def fileContents = new File(outputFile).text
println "File contents : " + fileContents
println ""
println "File Contents PrettyPrint"
println "========================="
println JsonOutput.prettyPrint(fileContents)

The above script produces the following output.

JSONBuilder Object : {"config":{"database":{"host":"example.com","port":3306,"type":"MySQL","user":"dbUser","pass":"dbPass","driver":"com.mysql.jdbc.Driver"},"threadPool":10,"useBridge":"Y"}}

JSON Pretty Printed Config 
==========================
{
    "config": {
        "database": {
            "host": "example.com",
            "port": 3306,
            "type": "MySQL",
            "user": "dbUser",
            "pass": "dbPass",
            "driver": "com.mysql.jdbc.Driver"
        },
        "threadPool": 10,
        "useBridge": "Y"
    }
}

Config details are written into the file 'config.json'

File contents : {"config":{"database":{"host":"example.com","port":3306,"type":"MySQL","user":"dbUser","pass":"dbPass","driver":"com.mysql.jdbc.Driver"},"threadPool":10,"useBridge":"Y"}}

File Contents PrettyPrint
=========================
{
    "config": {
        "database": {
            "host": "example.com",
            "port": 3306,
            "type": "MySQL",
            "user": "dbUser",
            "pass": "dbPass",
            "driver": "com.mysql.jdbc.Driver"
        },
        "threadPool": 10,
        "useBridge": "Y"
    }
}


Hope you found this example series helpful in manipulating the JSON data with Groovy scripts, for the simple use cases. However if you have a different (or advanced) scenario at hand, you are recommended to read the API for the variants of each class and its methods.

4. References

You may please refer the following URLs for further reading.

  1. Groovy Json from Groovy Language Documentation
  2. JsonSlurper Groovy API
  3. JsonBuilder Groovy API
  4. JsonOutput Groovy API

5. Download the Source Code

This is an example of how to read and write JSON data in Groovy, tested with the Command Prompt / Shell against Groovy Version 2.4.3.

Download
You can download the full source code of this example here: Groovy JSON Example

Raghavan Muthu

Raghavan alias Saravanan Muthu is a seasoned IT professional having more than 2 decades of experience on Java SE/EE based Application Architecture, Design, Development, Management and Administration for Banking, Insurance, Telecom, HealthCare and Automobile Industries, having a very good hands on experience on Multi-threaded, batch processing applications and Relational Databases. He is currently working as a Director of Engineering for one of the Product based companies in India that delivers the product on Health Care and Insurance Domain. He holds a Post Graduation (Master of Science), and a PG Degree on Big Data Engineering from Birla Institute of Technology and Science (BITS), Pilani, India. He is a Founder, Chief Executive Volunteer and a Web Master of a non-profit charity organization named SHaDE (http://shade.org.in).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button