Groovy - Creating JSON using JsonOutput
Groovy provides JsonOutput class as a primary tool to convert Groovy Maps, lists or even nested structures into JSON Strings. In this chapter, we're exploring them with examples.
Creating JSON from a Groovy Map
Example.groovy
import groovy.json.JsonOutput // Creating JSON from a map def employee = [name: "Alice", age: 28, city: "Seattle", dept: "Admin"] // convert Map to JSON def jsonFromMap = JsonOutput.toJson(employee) // prints Json println jsonFromMap
Output
When we run the above program, we will get the following result.
{"name":"Alice","age":28,"city":"Seattle","dept":"Admin"}
Creating JSON from a Groovy List
Example.groovy
import groovy.json.JsonOutput // Creating JSON from a list def fruits = ["apple", "banana", "mango"] // convert List to JSON def jsonFromList = JsonOutput.toJson(fruits) println jsonFromList
Output
When we run the above program, we will get the following result.
["apple","banana","mango"]
Creating JSON from a Groovy Nested Structure
Example.groovy
import groovy.json.JsonOutput
// Creating JSON from a nested structure
def stationary = [
id: 1,
items: [
[name: "Book", price: 17.99],
[name: "Pen", price: 2.51]
],
total: 20.50
]
def jsonFromNestedStruct = JsonOutput.toJson(stationary)
println jsonFromNestedStruct
Output
When we run the above program, we will get the following result.
{"id":1,"items":[{"name":"Book","price":17.99},{"name":"Pen","price":2.51}],"total":20.50}
Pretty Printing JSON
We can use JsonOutput.prettyPrint() to print JSON with proper indentation and breaks.
Example.groovy
import groovy.json.JsonOutput
// Creating JSON from a nested structure
def stationary = [
id: 1,
items: [
[name: "Book", price: 17.99],
[name: "Pen", price: 2.51]
],
total: 20.50
]
def jsonFromNestedStruct = JsonOutput.toJson(stationary)
def prettyJson = JsonOutput.prettyPrint(jsonFromNestedStruct)
println prettyJson
Output
When we run the above program, we will get the following result.
{
"id": 1,
"items": [
{
"name": "Book",
"price": 17.99
},
{
"name": "Pen",
"price": 2.51
}
],
"total": 20.50
}
Advertisements