
- Groovy Tutorial
- Groovy - Home
- Groovy - Overview
- Groovy - Environment
- Groovy - Basic Syntax
- Groovy - Data Types
- Groovy - Variables
- Groovy - Optionals
- Groovy - Numbers
- Groovy - Strings
- Groovy - Ranges
- Groovy - Lists
- Groovy - Maps
- Groovy - Dates & Times
Groovy Operators
- Groovy - Operators
- Groovy - Arithmetic Operators
- Groovy - Assignment Operators
- Groovy - Relational Operators
- Groovy - Logical Operators
- Groovy - Bitwise Operators
- Groovy - Spaceship Operator
- Groovy - in Operator
- Groovy - Elvis Operator
- Groovy - Safe Navigation Operator
- Groovy Operator Precedence & Associativity
Control Statements
- Groovy - Decision Making
- Groovy - If Else Statement
- Groovy - Switch Statement
- Groovy - Loops
- Groovy - For Loop
- Groovy - For-in Loop
- Groovy - While Loop
- Groovy - Do While Loop
- Groovy - Break Statement
- Groovy - Continue Statement
Groovy File Handling
- Groovy - File I/O
- Java - Create a File
- Java - Write to File
- Java - Append to File
- Java - Read Files
- Java - Delete Files
- Java - File Properties
- Java - File Existence and Type
- Java - File Size
- Java - File Permissions
- Java - Directories
- Java - Listing Directories
- Java - Filtering Files/Directories
- Java - Deleting Directories
- Java - Renaming Files/Directories
Groovy Error & Exceptions
- Groovy - Exception Handling
- Groovy - try-catch Block
- Groovy - try-with-resources
- Groovy - Multi-catch Block
- Groovy - Nested try Block
- Groovy - Finally Block
- Groovy - throw Exception
- Groovy - Exception Propagation
- Groovy - Built-in Exceptions
- Groovy - Custom Exception
Groovy Multithreading
- groovy - Multithreading
- groovy - Thread Life Cycle
- groovy - Creating a Thread
- groovy - Starting a Thread
- groovy - Joining Threads
- groovy - Naming Thread
- groovy - Thread Scheduler
- groovy - Thread Pools
- groovy - Main Thread
- groovy - Thread Priority
- groovy - Daemon Threads
- groovy - Shutdown Hook
Groovy Synchronization
- groovy - Synchronization
- groovy - Block Synchronization
- groovy - Static Synchronization
- groovy - Inter-thread Communication
- groovy - Thread Deadlock
- groovy - Interrupting a Thread
- groovy - Thread Control
- groovy - Reentrant Monitor
- Groovy - Methods
- Groovy - Methods
- Groovy - Optional parenthesis
- Groovy - Named Arguments
- Groovy - Closures as Arguments
- Groovy - Method Overloading
- Groovy - Method Scope and Visibility
- Groovy - isCase Method
- Groovy - Implicit Return
- Groovy - Variable Arguments
- Groovy - Regular Expressions
- Groovy - Regular Expressions
- Groovy - Defining Regular Expressions
- Groovy - Matcher Object
- Groovy - Regex Tasks
- Groovy - XML
- Groovy - XML
- Groovy - Parsing XML
- Groovy - Creating XML
- Groovy - Modifying XML
- Groovy - Querying XML
- Groovy - Simplified Notation
- Groovy - Closure based Querying
- Groovy - Closure based Creation
- Groovy - JSON
- Groovy - JSON
- Groovy - Parsing JSON
- Groovy - Creating JSON using JsonOutput
- Groovy - Creating JSON using JsonBuilder
- Groovy - Modifying JSON
- Groovy - Error Handling
- Groovy - Handling JSON Arrays
- Groovy - JSON Array Operations
- Groovy - JSON Objects
- Groovy - JSON Object Operations
- Groovy - Generics
- Groovy - Generics
- Groovy - Declaring Generic Types
- Groovy - Bound Type Parameters
- Groovy - Wild Cards
- Groovy - Miscellaneous
- Groovy - Object Oriented
- Groovy - Closures
- Groovy - Annotations
- Groovy - JMX
- Groovy - DSLS
- Groovy - Database
- Groovy - Builders
- Groovy - Command Line
- Groovy - Unit Testing
- Groovy - Template Engines
- Groovy - Meta Object Programming
- Groovy Useful Resources
- Groovy - Quick Guide
- Groovy - Useful Resources
- Groovy - Discussion
Groovy - JSON
This chapter covers how to we can use the Groovy language for parsing and producing JSON objects.
JSON Functions
Sr.No | Function & Libraries |
---|---|
1 |
JsonSlurper JsonSlurper is a class that parses JSON text or reader content into Groovy data Structures such as maps, lists and primitive types like Integer, Double, Boolean and String. |
2 |
JsonOutput This method is responsible for serialising Groovy objects into JSON strings. |
Parsing Data using JsonSlurper
JsonSlurper is a class that parses JSON text or reader content into Groovy data Structures such as maps, lists and primitive types like Integer, Double, Boolean and String.
Syntax
def slurper = new JsonSlurper()
JSON slurper parses text or reader content into a data structure of lists and maps.
The JsonSlurper class comes with a couple of variants for parser implementations. Sometimes you may have different requirements when it comes to parsing certain strings. Lets take an instance wherein one needs to read the JSON which is returned from the response from a web server. In such a case its beneficial to use the parser JsonParserLax variant. This parsee allows comments in the JSON text as well as no quote strings etc. To specify this sort of parser you need to use JsonParserType.LAX parser type when defining an object of the JsonSlurper.
Lets see an example of this given below. The example is for getting JSON data from a web server using the http module. For this type of traversal, the best option is to have the parser type set to JsonParserLax variant.
http.request( GET, TEXT ) { headers.Accept = 'application/json' headers.'User-Agent' = USER_AGENT response.success = { res, rd -> def jsonText = rd.text //Setting the parser type to JsonParserLax def parser = new JsonSlurper().setType(JsonParserType.LAX) def jsonResp = parser.parseText(jsonText) } }
Similarly the following additional parser types are available in Groovy −
The JsonParserCharArray parser basically takes a JSON string and operates on the underlying character array. During value conversion it copies character sub-arrays (a mechanism known as "chopping") and operates on them individually.
The JsonFastParser is a special variant of the JsonParserCharArray and is the fastest parser. JsonFastParser is also known as the index-overlay parser. During parsing of the given JSON String it tries as hard as possible to avoid creating new char arrays or String instances. It just keeps pointers to the underlying original character array only. In addition, it defers object creation as late as possible.
The JsonParserUsingCharacterSource is a special parser for very large files. It uses a technique called "character windowing" to parse large JSON files (large means files over 2MB size in this case) with constant performance characteristics.
Parsing Text
Lets have a look at some examples of how we can use the JsonSlurper class.
import groovy.json.JsonSlurper class Example { static void main(String[] args) { def jsonSlurper = new JsonSlurper() def object = jsonSlurper.parseText('{ "name": "John", "ID" : "1"}') println(object.name); println(object.ID); } }
In the above example, we are −
First creating an instance of the JsonSlurper class
We are then using the parseText function of the JsonSlurper class to parse some JSON text.
When we get the object, you can see that we can actually access the values in the JSON string via the key.
The output of the above program is given below −
John 1
Parsing List of Integers
Lets take a look at another example of the JsonSlurper parsing method. In the following example, we are pasing a list of integers. You will notice from The following codethat we are able to use the List method of each and pass a closure to it.
import groovy.json.JsonSlurper class Example { static void main(String[] args) { def jsonSlurper = new JsonSlurper() Object lst = jsonSlurper.parseText('{ "List": [2, 3, 4, 5] }') lst.each { println it } } }
The output of the above program is given below −
List=[2, 3, 4, 5]
Parsing List of Primitive Data types
The JSON parser also supports the primitive data types of string, number, object, true, false and null. The JsonSlurper class converts these JSON types into corresponding Groovy types.
The following example shows how to use the JsonSlurper to parse a JSON string. And here you can see that the JsonSlurper is able to parse the individual items into their respective primitive types.
import groovy.json.JsonSlurper class Example { static void main(String[] args) { def jsonSlurper = new JsonSlurper() def obj = jsonSlurper.parseText ''' {"Integer": 12, "fraction": 12.55, "double": 12e13}''' println(obj.Integer); println(obj.fraction); println(obj.double); } }
The output of the above program is given below −
12 12.55 1.2E+14
JsonOutput
Now lets talk about how to print output in Json. This can be done by the JsonOutput method. This method is responsible for serialising Groovy objects into JSON strings.
Syntax
Static string JsonOutput.toJson(datatype obj)
Parameters − The parameters can be an object of a datatype Number, Boolean, character,String, Date, Map, closure etc.
Return type − The return type is a json string.
Example
Following is a simple example of how this can be achieved.
import groovy.json.JsonOutput class Example { static void main(String[] args) { def output = JsonOutput.toJson([name: 'John', ID: 1]) println(output); } }
The output of the above program is given below −
{"name":"John","ID":1}
The JsonOutput can also be used for plain old groovy objects. In the following example, you can see that we are actually passing objects of the type Student to the JsonOutput method.
import groovy.json.JsonOutput class Example { static void main(String[] args) { def output = JsonOutput.toJson([ new Student(name: 'John',ID:1), new Student(name: 'Mark',ID:2)]) println(output); } } class Student { String name int ID; }
The output of the above program is given below −
[{"name":"John","ID":1},{"name":"Mark","ID":2}]