Groovy 转换JSON和生产JSON

时间:2022-10-12 09:20:37

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 {

static
main(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 {

static
main(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.

Groovy 转换JSON和生产JSON的更多相关文章

  1. Json对象与Json字符串互转(4种转换方式)

    Json字符与Json对象的相互转换方式有很多,接下来将为大家一一介绍下,感兴趣的朋友可以参考下哈,希望可以帮助到你 1>jQuery插件支持的转换方式: 复制代码代码如下: $.parseJS ...

  2. Javascript数值转换(string,int,json)

    数值: 在JavaScript中,数值转换一般有三种方式: 一.Number(param)函数:param可以用于任何数据类型 1.1 param是Boolean值,true和false分别转换为1和 ...

  3. 前端页面使用 Json对象与Json字符串之间的互相转换

    前言 在前端页面很多时候都会用到Json这种格式的数据,最近没有前端,后端的我也要什么都要搞,对于Json对象与Json字符串之间的转换终于摸清楚了几种方式,归纳如下! 一:Json对象转换为json ...

  4. Json串到json对象的转换

    JSON(JavaScript Object Notation) JS对象符号 是一种轻量级的数据交换格式 JavaScript eval()函数实现 (一) 标准格式 function JsonFo ...

  5. javascript、js操作json方法总结(json字符创转换json对象)

    相信前端的同学们对json并不陌生,接触过很多.但是很少人知道json的全称是什么,哈哈,我也是查资 料知道的.(JSON JavaScript Object Notation是一种轻量级的数据交换格 ...

  6. json字符串转换成json对象,json对象转换成字符串,值转换成字符串,字符串转成值

    一.json相关概念 json,全称为javascript object notation,是一种轻量级的数据交互格式.采用完全独立于语言的文本格式,是一种理想的数据交换格式. 同时,json是jav ...

  7. Gson解析json字符串、json数组转换成对象

    实体类: public class Product { private int id; private String name; private String date; public int get ...

  8. Json对象与Json字符串的转化、JSON字符串与Java对象的转换

    一.Json对象与Json字符串的转化 1.jQuery插件支持的转换方式: $.parseJSON( jsonstr ); //jQuery.parseJSON(jsonstr),可以将json字符 ...

  9. JSON.stringify()方法是将一个javascript值(对象或者数组)转换成为一个JSON字符串;JSON.parse()解析JSON字符串,构造由字符串描述的javascript值或对象

    JSON.stringify()方法是将一个javascript值(对象或者数组)转换成为一个JSON字符串:JSON.parse()解析JSON字符串,构造由字符串描述的javascript值或对象

随机推荐

  1. matplotlib 高级用法实例--共享x轴

    http://localhost:8888/notebooks/duanqs/matplotlib_advanced_example.ipynb 我不会弄呀, 刚才从matplotlib文档里吧示例用 ...

  2. Android中ListView的用法

    使用方法1 显示简单的文本 在layout文件中像加入普通控件一样在layout文件中引入ListView <ListView android:id="@+id/list_view&q ...

  3. Android之指南针(电子罗盘)学习

    点我下载源码 5月12日更新到V5版:http://download.csdn.net/detail/weidi1989/5364243 今天,在小米的开源项目中下载了一个指南针源码学习了一下,感觉不 ...

  4. Node&period;js v0&period;10&period;31API手冊-控制台

    Node.js v0.10.31API手冊-文件夹 控制台 Object 用于向 stdout 和 stderr 打印字符.类似于大部分 Web 浏览器提供的 console 对象函数,在这里则是输出 ...

  5. 20155227 实现mypwd

    20155227 实现mypwd 1 学习pwd命令 2 研究pwd实现需要的系统调用(man -k; grep),写出伪代码 3 实现mypwd 4 测试mypwd 课堂学习笔记 实现mypwd 在 ...

  6. javaweb笔记—01(编程英语、常识、Tomcat配置问题)

    第一部分: 编程英语: legal:adj. 法律的:合法的:法定的 Userful :出版商  sponsor: n. 赞助者:主办者:保证人 | vt. 赞助:发起 essential:n. 本质 ...

  7. Hexo之部署github

    最近开始学NodeJs,准备也在github上弄个一个Hexo博客练练过程中遇到一些问题总结一下.希望对遇到同样问题的同学能有个帮助少走一些弯路. - 其实用windows或mac客户端直接去同步很顺 ...

  8. 关于switch语句中使用String类型的实现原理

    在Java 7 以后,switch语句可以用作String类型上. 从本质来讲,switch对字符串的支持,其实也是int类型值的匹配.它的实现原理如下: 通过对case后面的String对象调用ha ...

  9. NOIP2013 提高组 Day2

    期望得分:100+100+30+=230+ 实际得分:100+70+30=200 T2 觉得题目描述有歧义: 若存在2i却不存在2i+1,自己按不合法做的,实际是合法的 T3  bfs 难以估分 虽然 ...

  10. IIS6中给Framework2&comma;。0站点的虚拟目录(2&period;0版本)下发布Web API项目(4&period;0版本)问题处理

    Web-API项目以虚拟目录形式部署到IIS6/IIS7 若原有站点为Framework2.0版本,在此站点(或虚拟目录站点)下,新增API虚拟目录,然后选择Framework4.0版本,IIS6和I ...