Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Parsing JSON



Groovy provides JsonSlurper class as a primary object to parse a JSON string and stream it into Groovy objects. We can parse JSON from varying sources like string, file, url, reader or inputstream and so on. In this chapter, we're exploring them with examples.

Parsing JSON from a String

Example.groovy

import groovy.json.JsonSlurper

def jsonString = '''
{
   "name": "John",
   "age": 35,
   "city": "Dalas",
   "skills": ["Java", "Groovy", "Python"],
   "address": {
      "street": "Avenue 2",
      "zip": "60301"
   }
}
'''

def jsonSlurper = new JsonSlurper()
def employee = jsonSlurper.parseText(jsonString)

// Now 'employee' represents a Groovy map
// prints John
println employee.name       
// prints 35
println employee.age        
// print zip
println employee.address.zip 
// prints Groovy
println employee.skills[1]  

Output

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

John
35
60301
Groovy

Parsing JSON from a File

Assuming data.json in the current directory with following content −

{
  "userId": 1,
  "id": 1,
  "title": "A sample user",
  "completed": false
}

Example.groovy

import groovy.json.JsonSlurper

def data = new File('data.json')

try {
    def data = new JsonSlurper().parse(data)
    println data.userId
} catch (Exception e) {
    println "Error processing JSON file: ${e.getMessage()}"
}

Output

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

1

Parsing JSON from a URL

We can parse JSON from URL easily. We're using a public URL resulting in following JSON −

{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

Example.groovy

import groovy.json.JsonSlurper

try {
    def url = new URL('https://jsonplaceholder.typicode.com/todos/1')
    def response = new JsonSlurper().parse(url)
    println response.userId
} catch (Exception e) {
    println "Error using URL: ${e.getMessage()}"
}

Output

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

1

Parsing JSON from an InputStream or a Reader

Example.groovy

import groovy.json.JsonSlurper

def jsonString = '''
{
   "name": "John",
   "age": 35,
   "city": "Dalas",
   "skills": ["Java", "Groovy", "Python"],
   "address": {
      "street": "Avenue 2",
      "zip": "60301"
   }
}
'''


def jsonStream = new ByteArrayInputStream(jsonString.getBytes())
def employeeFromStream = new JsonSlurper().parse(jsonStream)
println employeeFromStream.city

def jsonReader = new StringReader(jsonString)
def employeeFromReader = new JsonSlurper().parse(jsonReader)
println employeeFromReader.age

Output

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

Dalas
35
Advertisements