Groovy - JSON

This chapter covers how to we can use the Groovy language for parsing and producing JSON objects.
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.
JsonOutput
This method is responsible for serialising Groovy objects into JSON strings.
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.
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. Let’s take an instance wherein one needs to read the JSON which is returned from the response from a web server. In such a case it’s 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.
Let’s 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 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 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.
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.
Let’s 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
First creating an instance of the JsonSlurper class
We are then using the parseText function of the JsonSlurper class to parse some JSON text.
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.
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

Let’s 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]

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 

Now let’s 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.
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.
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}]


    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page