文章目录






一、Groovy 对象转为 json 字符串 ( 使用 JsonBuilder 进行转换 )



声明 Student 类 , 在其中声明 2 2 2 个成员 , ​​name​​​ 和 ​​age​​ ;

class Student {
def name
def age
}

创建 Student 对象时 , 构造函数中为这两个成员赋值

def student = new Student(name: "Tom", age: 18)

创建 json 生成器 JsonBuilder 对象 , 构造函数中传入 Student 对象 , 即可完成 json 转换 , 将 Student 对象转为了 json 字符串 ;

// json 生成器
def jsonBuilder = new JsonBuilder(student)
println jsonBuilder.toString()



代码示例 :

import groovy.json.JsonBuilder

class Student {
def name
def age
}

def student = new Student(name: "Tom", age: 18)

// json 生成器
def jsonBuilder = new JsonBuilder(student)
println jsonBuilder.toString()

执行结果 :

{"age":18,"name":"Tom"}






二、使用 JsonOutput 将指定类型对象转为 json 字符串



JsonOutput 可以将 Map , URL , String , Number , Date , UUID , Boolean 等类型的对象转为 json 字符串 ;

【Groovy】json 序列化 ( 类对象转为 json 字符串 | 使用 JsonBuilder 进行转换 | 使用 JsonOutput 进行转换 | 将 json 字符串格式化输出 )_Gradle

将 Student 对象转为 json 代码如下 :

// 将 Student 对象转为 json
def json = JsonOutput.toJson(student)
println json

执行结果 :

{"age":18,"name":"Tom"}






三、将 json 字符串格式化输出



使用 ​​JsonOutput.prettyPrint(json)​​ 可以将 json 进行格式化输出 ,

函数原型如下 :

/**
* Pretty print a JSON payload.
*
* @param jsonPayload
* @return a pretty representation of JSON payload.
*/
public static String prettyPrint(String jsonPayload) {
}

将 ​​{"age":18,"name":"Tom"}​​ 使用上述格式化输出 ,

// 格式化输出 json 数据
println JsonOutput.prettyPrint(json)

输出结果 :

{
"age": 18,
"name": "Tom"
}






四、完整代码示例



完整代码示例 :

import groovy.json.JsonBuilder
import groovy.json.JsonOutput

class Student {
def name
def age
}

def student = new Student(name: "Tom", age: 18)

// json 生成器
def jsonBuilder = new JsonBuilder(student)
println jsonBuilder.toString()

// 将 Student 对象转为 json
def json = JsonOutput.toJson(student)
println json

// 格式化输出 json 数据
println JsonOutput.prettyPrint(json)

执行结果 :

{"age":18,"name":"Tom"}
{"age":18,"name":"Tom"}
{
"age": 18,
"name": "Tom"
}

【Groovy】json 序列化 ( 类对象转为 json 字符串 | 使用 JsonBuilder 进行转换 | 使用 JsonOutput 进行转换 | 将 json 字符串格式化输出 )_Groovy_02