Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Creating JSON using JsonBuilder



Groovy provides JsonBuilder class which provides a fine-grained control over JSON structure. JsonBuilder provides a declarative and closure based approach to build the JSON. It resembles MarkupBuilder for XML generation.

Creating JSON Using JsonBuilder

Example.groovy

import groovy.json.JsonBuilder

def builder = new JsonBuilder()

builder {
   employee {
      name 'Alice'
      age 28
      city 'Seattle'
      address {
         street '789 Pine Ln'
         zip '10115'
      }
      dept 'Admin'
   }
}

def json = builder.toPrettyString() 
println json

Output

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

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

Creating JSON Array using Builder

Example.groovy

import groovy.json.JsonBuilder

def builder = new JsonBuilder()

builder([
   [  name: 'Julie', age: 32, id: 1 ],
   [  name: 'Henry', age: 27, id: 2 ]
])

println builder.toPrettyString()

Output

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

[
    {
        "name": "Julie",
        "age": 32,
        "id": 1
    },
    {
        "name": "Henry",
        "age": 27,
        "id": 2
    }
]

Using Groovy Variables and Expresssions within JsonBuilder

Example.groovy

import groovy.json.JsonBuilder

def itemName = "Laptop"
def itemPrice = 99.99

def builder = new JsonBuilder()
builder.item {
   name itemName
   price itemPrice
   discount itemPrice * 0.2
   finalPrice itemPrice * 0.8
}

println builder.toPrettyString()

Output

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

{
    "item": {
        "name": "Laptop",
        "price": 99.99,
        "discount": 19.998,
        "finalPrice": 79.992
    }
}
Advertisements