国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Groovy 轉換JSON和生產JSON

2019-11-14 23:41:56
字體:
來源:轉載
供稿:網友
Groovy 轉換JSON和生產JSON

Groovy 類和JSON之間的相互轉換,主要在groovy.json包下面

1. JsonSlurper

JsonSlurper 這個類用于轉換JSON文本或從Groovy 數據結構中讀取內容例如map、list和一些基本的數據類型如Integer, Double, Boolean和String.

這個類有一系列重載的Parse的方法和一些指定特殊的方法,例如parseText,parseFile..下一個離職我們將以parseText使用為例,將JSON 字符串轉換為list 和map對象。其他parse開頭的方法與之類似只是參數不同而已,

import groovy.json.JsonSlurper

class ParseJson_01 {

staticmain(args) {

def jsonSlurper = new JsonSlurper()

def object = jsonSlurper.parseText('{ "name": "John Doe" } ')

assert object instanceof Map

assert object.name == 'John Doe'

}

}

JsonSlurper除了maps支持,JSON 數據轉被換成lists。

import groovy.json.JsonSlurper

class ParseJson_02 {

staticmain(args) {

def jsonSlurper = new JsonSlurper()

def object = jsonSlurper.parseText('{ "myList": [4, 8, 15, 16, 23, 42] }')

assert object instanceof Map

assert object.myList instanceof List

assert object.myList == [4, 8, 15, 16, 23, 42]

}

}

JSON支持一下的的標準的原始數據類型:string 、number、object、true、false和null. JsonSlurper把這些解析成相應的Groovy類型.

def jsonSlurper = new JsonSlurper()

def object = jsonSlurper.parseText '''

{ "simple": 123,

"fraction": 123.66,

"exponential": 123e12

}'''

assert object instanceof Map

assert object.simple.class == Integer

     assert object.fraction.class == BigDecimal

As JsonSlurper is returning pure Groovy object instances without any special JSON classes in the back, its usage is transparent. In fact, JsonSlurper results conform to GPath exPRessions. GPath is a powerful expression language that is supported by multiple slurpers for different data formats (xmlSlurper for XML being one example).

For more details please have a look at the section on GPath expressions.

Json

和groovy 對應的數據類型

JSON

Groovy

string

java.lang.String

number

java.lang.BigDecimal or java.lang.Integer

object

java.util.LinkedHashMap

array

java.util.ArrayList

true

true

false

false

null

null

date

java.util.Date based on the yyyy-MM-dd'T'HH:mm:ssZ date format

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

1.1. Parser Variants

JsonSlurper comes with a couple of parser implementations. Each parser fits different requirements, it could well be that for certain scenarios the JsonSlurper default parser is not the best bet for all situations. Here is 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 parser. 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 are put into long-term caches care must be taken as the map objects might not be 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 copy of the original buffer. Recommendation is to use the JsonFastParser for JSON buffers under 2MB and keeping the long-term cache restriction in mind.
  • The JsonParserLax is a special variant of the JsonParserCharArray parser. It has similar performance characteristics as JsonFastParser but differs in that it isn't exclusively relying on the ECMA-404 JSON grammar. For example it allows for comments, no quote strings etc.
  • 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 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 JsonParserType with a call to JsonSlurper#setType().

def jsonSlurper = new JsonSlurper(type: JsonParserType.INDEX_OVERLAY)
def object = jsonSlurper.parseText('{ "myList": [4, 8, 15, 16, 23, 42] }')

assert object instanceof Map
assert object.myList instanceof List
assert object.myList == [4, 8, 15, 16, 23, 42]
2. JsonOutput

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

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

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

def json = JsonOutput.toJson([name: 'John Doe', age: 42])

assert json == '{"name":"John Doe","age":42}'

JsonOutput does not only support primitive, maps or list data types to be serialized to JSON, it goes further and even has support for serialising POGOs, that is, 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 is 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":42}'

assert JsonOutput.prettyPrint(json) == '''/
{
    "name": "John Doe",
    "age": 42
}'''.stripIndent()

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

Another way to create JSON from Groovy is to use the JsonBuilder or StreamingJsonBuilder. Both builders provide a DSL which allows to formulate an object graph which is then converted to JSON at some point.

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


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 柳江县| 浮梁县| 台东县| 独山县| 郓城县| 中宁县| 鄂尔多斯市| 巴青县| 乳山市| 玉山县| 根河市| 县级市| 三江| 和林格尔县| 黄陵县| 蚌埠市| 年辖:市辖区| 祁阳县| 张掖市| 隆化县| 彭泽县| 台南市| 景泰县| 石泉县| 勐海县| 新竹县| 县级市| 平舆县| 阳泉市| 阿瓦提县| 丹江口市| 团风县| 广西| 双城市| 道孚县| 汽车| 左云县| 西和县| 孟州市| 湘乡市| 昂仁县|