1. 简介

本文将介绍在Groovy应用中处理JSON的实用技巧和示例。首先需要配置项目依赖,确保以下Maven配置生效:

<build>
    <plugins>
        <!-- 其他插件 -->
        <plugin>
            <groupId>org.codehaus.gmavenplus</groupId>
            <artifactId>gmavenplus-plugin</artifactId>
            <version>3.0.0</version>
        </plugin>
    </plugins>
</build>
<dependencies>
    <!-- 其他依赖 -->
    <dependency>
        <groupId>org.codehaus.groovy</groupId>
        <artifactId>groovy-all</artifactId>
        <version>4.0.21</version>
    </dependency>
</dependencies>

最新Maven插件版本可在这里查看,groovy-all最新版本在这里

2. 将Groovy对象转换为JSON

Groovy中对象转JSON非常简单。假设我们有一个Account类:

class Account {
    String id
    BigDecimal value
    Date createdAt
}

使用JsonOutput类的静态方法toJson()即可完成转换:

Account account = new Account(
    id: '123', 
    value: 15.6,
    createdAt: new SimpleDateFormat('MM/dd/yyyy').parse('01/01/2018')
) 
println JsonOutput.toJson(account)

输出结果:

{"value":15.6,"createdAt":"2018-01-01T02:00:00+0000","id":"123"}

2.1. 自定义JSON输出

⚠️ 注意:默认日期格式可能不符合需求。从Groovy 2.5开始,groovy.json包提供了专用工具类JsonGenerator

JsonGenerator generator = new JsonGenerator.Options()
  .dateFormat('MM/dd/yyyy')
  .excludeFieldsByName('value')
  .build()

println generator.toJson(account)

输出结果(排除value字段并格式化日期):

{"createdAt":"01/01/2018","id":"123"}

2.2. 格式化JSON输出

默认输出是单行压缩格式,处理复杂对象时难以阅读。使用prettyPrint方法美化输出:

String json = generator.toJson(account)
println JsonOutput.prettyPrint(json)

格式化后的输出:

{
    "value": 15.6,
    "createdAt": "01/01/2018",
    "id": "123"
}

3. 将JSON解析为Groovy对象

使用JsonSlurper类完成JSON到对象的转换。它提供多个重载方法,如parseTextparseFile等。

✅ 简单示例:将JSON字符串转为Account对象

def jsonSlurper = new JsonSlurper()
def account = jsonSlurper.parseText('{"id":"123", "value":15.6 }') as Account

不指定类型时,默认返回Map对象,利用Groovy动态类型特性可灵活处理。

3.1. 处理特殊解析场景

❌ 默认解析器(JsonParserType.CHAR_BUFFER)可能无法正确处理日期等特殊类型:

def jsonSlurper = new JsonSlurper()
def account = jsonSlurper.parseText('{"id":"123","createdAt":"2018-01-01T02:00:00+0000"}') as Account

结果:所有属性均为null(日期被错误解析为字符串)

✅ 解决方案:使用INDEX_OVERLAY解析器避免字符串/字符数组创建:

def jsonSlurper = new JsonSlurper(type: JsonParserType.INDEX_OVERLAY)
def account = jsonSlurper.parseText('{"id":"123","createdAt":"2018-01-01T02:00:00+0000"}') as Account

现在能正确创建Account实例。

3.2. 解析器变体

JsonParserType提供多种实现:

  • LAX:宽松解析模式,支持注释、无引号字符串等
  • CHARACTER_SOURCE:专为解析大文件优化

4. 总结

本文通过实际示例展示了Groovy中JSON处理的核心技巧:

  • 对象转JSON:JsonOutput + JsonGenerator定制输出
  • JSON转对象:JsonSlurper灵活解析
  • 特殊场景处理:日期格式、大文件解析等

深入了解可参考Groovy官方文档,完整示例代码见GitHub仓库


原始标题:Working with JSON in Groovy