Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Groovy JSON


May 14, 2021 Groovy


Table of contents


This chapter describes how to use the Groovy language to parse and generate JSON objects.

JSON function

Function Library
JsonSlurper

Json Slurper is a class that parses JSON text or reader content into Groovy data

Structures such as maps, lists, and original types, such as integers, doubles, booleans, and strings.

JsonOutput This method is responsible for serializing groovy objects into JSON strings.

Use Jason Slurper to parse the data

JsonSlurper is a class that parses JSON text or reader content into Groovy data structures, such as maps, lists, and original types such as Integer, Double, Boolean, and String.

Syntactic

def slurper = new JsonSlurper()

JSON slurper parses text or reader content into data structures for lists and maps.

The JsonSlurper class brings its own variants for parser implementations. S ometimes, you may have different requirements when parsing certain strings. b20> n this case, it is useful to use the parser Jason Parser Lax variable. ts. o specify this type of parser, you need to use the JohnsonParserType.LAX parser type when defining Jason Slurper's objects.

Let's look at the following example. A n example is using the http module to get JSON data from a Web server. For this type of traversal, the best option is to set the parser type to the JohnsonParserLax 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 JsonParser CharArray parser basically uses a JSON string and operates on an array of underlying characters. During a value conversion, it copies sub-arrays of characters (a mechanism called choppers) and manipulates them separately.

  • Jason FastParser is a special variant of Jason Parser CharArray and is the fastest parser. b20> uring parsing a given JSON string, it does its best to avoid creating new character arrays or String instances. le. n addition, it delays object creation as late as possible.

  • Jason Parser UsingCharacterSource is a special parser for very large files. It uses a technique called character windowing to parse large JSON files with constant performance characteristics (large means files larger than 2MB in size).

Text resolution

Let's take a look at some examples of how to use the Jason Slurper 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 example above, we are -

  • Start by creating an instance of the Jason Slurper class

  • Then we use the parseText function of the Jason Slurper 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 by key.

The output of the above program is as follows -

John 
1

Resolve the integer list

Let's take a look at another example of the Jason Slurper parsing method. I n the following example, we'll list the integers. You'll notice the following code, we can use each List method and pass a closure.

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 as follows -

List=[2, 3, 4, 5, 23, 42]

Resolve the list of basic data types

JSON parsers also support raw data types for strings, numbers, objects, true, false, and null. The JsonSlurper class converts these JSON types to the appropriate Groovy types.

The following example shows how to parse the JSON string using Jason Slurper. Here you can see that Jason Slurper is able to parse individual projects into their own basic 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 as follows -

12 
12.55 
1.2E+14 

JsonOutput

Now let's talk about how to print out in Johnson. T his can be done through the JohnsonOutput method. This method is responsible for serializing groovy objects into JSON strings.

Syntactic

Static string JsonOutput.toJson(datatype obj)

Parameters - Parameters can be objects of data type - numbers, booleans, characters, strings, dates, maps, closures, etc.

Return type - Return type is a JSON string.

Example

Here's a simple example of how to do this.

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 as follows -

{"name":"John","ID":1}

Jason Output can also be used for normal old Groovy objects. In the following example, you can see that we are actually passing objects of the Sentent type to the JohnsonOutput 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 as follows -

[{"name":"John","ID":1},{"name":"Mark","ID":2}]