[JSON] Parsing and producing JSON

Source: Internet
Author: User
Tags tojson

Http://www.groovy-lang.org/json.html

Groovy comes with integrated support for converting between Groovy objects and JSON. The classes dedicated to JSON serialisation and parsing is found in the package groovy.json .

1. Jsonslurper

JsonSlurperis a class this parses JSON text or reader content into Groovy data structures (objects) such as maps, lists and primitive Types like Integer , Double , Boolean and String .

The class comes with a bunch of overloaded parse methods plus some special methods such parseText as, and parseFile others. For the next example we'll use the parseText method. It parses a JSON and String recursively converts it to a list or map of objects. The other parse* methods is similar in this they return a JSON but for String different parameter types.

def jsonslurper = new Jsonslurper () def object = Jsonslurper.parsetext (' {"name": "John Doe"}/* Some comment */') assert O Bject instanceof Mapassert Object.name = = ' John Doe '

Notice The result is a plain map and can be handled like a normal Groovy object instance. JsonSlurperparses the given JSON as defined by the ECMA-404 JSON interchange standard plus support for JavaScript comments and Dates.

In addition to maps JsonSlurper supports JSON arrays which is being converted to lists.

def jsonslurper = new Jsonslurper () def object = Jsonslurper.parsetext (' {"MyList": [4, 8, (+), +, +]} ') Assert object instanceof Mapassert object.mylist instanceof Listassert object.mylist = = [4, 8, 15, 16, 23, 42]

The JSON standard supports the following primitive data types:string, number, object, true and false null . JsonSlurper conve RTS these JSON types into corresponding Groovy types.

def jsonslurper = new Jsonslurper () def object = Jsonslurper.parsetext "'    {" simple ": 123,      " fraction ": 123.66,
    "exponential": 123e12    } "Assert object instanceof mapassert object.simple.class = = Integerassert Object.fraction.class = = Bigdecimalassert Object.exponential.class = = BigDecimal

JsonSlurperas is returning pure Groovy object instances without any special JSON classes in the back, it usage is transparent. In fact, the JsonSlurper results conform to gpath expressions. Gpath is a powerful expression language this is supported by multiple slurpers for different data formats (for XmlSlurper XML b Eing One example).

For more details, there is a look at the Gpath expressions.

The following table gives an overview of the JSON types and the corresponding Groovy data types:

JSON Groovy

String

java.lang.String

Number

java.lang.BigDecimalOrjava.lang.Integer

Object

java.util.LinkedHashMap

Array

java.util.ArrayList

True

true

False

false

Null

null

Date

java.util.DateBased on the yyyy-MM-dd’T’HH:mm:ssZ date format

Whenever a value null in JSON was, JsonSlurper supplements it with the Groovy null value. This was in contrast to other JSON parsers, that represent a null value with a library-provided singleton object.
1.1. Parser variants

JsonSlurperComes with a couple of parser implementations. Each parser fits different requirements, it could well being that for certain scenarios the JsonSlurper default parser are not the B EST bet for all situations. Here's an overview of the shipped parser implementations:

  • 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.

  • The jsonfastparser is a special variant of the Jsonparserchararray and is the fastest par Ser. However, it is not the default parser for a reason. Jsonfastparser is a so-called 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 keeps pointers to the underlying original character array only. In addition, it defers object creation as late as possible. If parsed maps is put into long-term caches care must being taken as the map objects might not being created and still consist of pointer to the original char-buffer only. However, Jsonfastparser comes with a special chop mode which dices up the char buffer early to keep a small c Opy of the original buffer. Recommendation is to use the jsonfastparser for JSON buffers under 2MB and keeping the long-term cache Restri Ction in mind.

  • The is JsonParserLax a special variant of the JsonParserCharArray parser. It has similar performance characteristics as and differs in so JsonFastParser it isn ' t exclusively relying on the ECMA-404 JSON Grammar. For example it allows for comments, no quote strings etc.

  • The is JsonParserUsingCharacterSource 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 default parser implementation for JsonSlurper is JsonParserCharArray . The JsonParserType enumeration contains constants for the parser implementations described above:

implementation constant

Jsonparserchararray

Jsonparsertype#char_buffer

Jsonfastparser

Jsonparsertype#index _overlay

Jsonparserlax

Jsonparsertype#lax

jsonparserusingcharactersource

Jsonparsertype#character_source

Changing the parser implementation is as easy as setting the with JsonParserType a call to JsonSlurper#setType() .

def jsonslurper = new Jsonslurper (Type:JsonParserType.INDEX_OVERLAY) def object = Jsonslurper.parsetext (' {"MyList": [4, 8, (4, 8, 15, 1) Assert object instanceof Mapassert object.mylist instanceof listassert object.mylist = = 6, 23, 42]

2. Jsonoutput

JsonOutputis responsible for serialising Groovy objects into JSON strings. It can be seen as companion object to Jsonslurper, being a JSON parser.

JsonOutputComes with overloaded, static toJson methods. Each toJson implementation takes a different parameter type. The static method can either is used directly or by importing the methods with a static import statement.

The result of a call is toJson a String containing the JSON code.

def JSON = Jsonoutput.tojson ([name: ' John Doe ', age:42]) assert json = = ' {' name ': ' John Doe ', ' age ': 42} '

JsonOutputdoes not only support primitive, maps or list data types to is serialized to JSON, it goes further and even have support fo R serialising Pogos, that's, Plain-old Groovy objects.

Class Person {String name}def json = Jsonoutput.tojson ([New Person (name: ' John '), new person (name: ' Max ')]) assert JSON = = ' [{' name ': ' John '},{' name ': ' Max '}] '

As we saw in previous examples, the JSON output was not pretty printed per default. However, the prettyPrint method in JsonSlurper comes to rescue for this task.

def JSON = Jsonoutput.tojson ([name: ' John Doe ', age:42]) assert json = = ' {' name ': ' John Doe ', ' age ': ' [] ' Assert jsonoutput.pr Ettyprint (JSON) = = ' ' {'    name ': ' John Doe ', ' age ': ' A ' '    . Stripindent ()

prettyPrintTakes a as single String parameter. It must not being used JsonOutput in conjunction with the other methods, it can is applied on arbitrary JSON String instances.

Another-to-create JSON from Groovy was to use the JsonBuilder or StreamingJsonBuilder . Both Builders provide a DSL which allows to formulate an object graph which are then converted to JSON at some point.

For more details on builders, there is a look at the builders chapter which covers both JSON builders in great depth.

[JSON] Parsing and producing JSON

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.