Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Handling JSON Objects



In groovy, we can handle JSON objects easily using JsonSlurper. Whenever a JSON object is encountered as enclosed in curly braces, {}, JsonSlurper converts it into a Map instance. The keys and values of JSON objects are mapped to key-value pairs in the Map. In this chapter, we'll demonstrating scenarios of handling JSON objects using JsonSlurper and JsonBuilder.

Parsing JSON Object using JsonSlurper

Example.groovy

import groovy.json.JsonSlurper

def jsonObjectText = '''
{  
   "name": "Julie",
   "age": 32, 
   "id": 1, 
   "isManager": false,
   "courses" : ["java", "python"]
},
'''

def slurper = new JsonSlurper()

def employee = slurper.parseText(jsonObjectText)

// prints groovy.json.internal.LazyMap
println employee.getClass().name
// prints the map
println employee

Output

When we run the above program, we will get the following result.

groovy.json.internal.LazyMap
[age:32, courses:[java, python], id:1, isManager:false, name:Julie]

Here we can see that JSON object is converted to a Map.

Parsing Nested JSON Objects using JsonSlurper

We can parse nested JSON objects as well. JsonSlurper automatically converts them into nested m as shown below −

Example.groovy

import groovy.json.JsonSlurper

def nestedMapJsonString = '''
{
   "name": "Alice",
   "age": 28,
   "city": "Seattle",
   "address": {
      "street": "789 Pine Ln",
      "zip": "10115"
   },
   "dept": "Admin"
}
'''

def jsonSlurper = new JsonSlurper()
def nestedData = jsonSlurper.parseText(nestedMapJsonString)

// prints 10155
println nestedData.address.zip

Output

When we run the above program, we will get the following result.

10155

Creating JSON Object using JsonBuilder

We can create JSON Objects easliy using JsonBuilder. Object structures can be defined using closures as shown in example below −

Example.groovy

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

def employee = [
   name: 'Julie', 
   age: 32, 
   id: 1
]

def builder = new JsonBuilder()
builder {
   name employee.name
   age employee.age
   id employee.id
   department "Admin"
}

def jsonOutput = JsonOutput.prettyPrint(builder.toString())
println jsonOutput

Output

When we run the above program, we will get the following result.

{
    "name": "Julie",
    "age": 32,
    "id": 1,
    "department": "Admin"
}
Advertisements