groovy 打印json_使用Groovy进行JSON输出

I have been experimenting with the groovy Jsonbuilder as you can see below trying to look at different ways to build JSON objects and arrays. After things started to make sense, I tried expanding to what is shown below. The question I have is, why does "content" show up in the json pretty string output? I actually have another json object displaying this.class information in json string outputs.

Any ideas? I'm new to this, so it could definitely be an obvious one.

def tt = ["test", "test1"]

def jjj = "jason"

def js3 = new groovy.json.JsonBuilder()

def js2 = new groovy.json.JsonBuilder(tt);

js3 hello: "$jjj", "$jjj": tt

def js4 = new groovy.json.JsonBuilder()

def result = js4([sdn: js3, openflow: js2, type: 3])

println js4.toPrettyString();

{

"sdn": {

"content": {

"hello": "jason",

"jason": [

"test",

"test1"

]

}

},

"openflow": {

"content": [

"test",

"test1"

]

},

"type": 3

}

解决方案

The problem can be restated as...

why does this:

import groovy.json.*

def js3 = new JsonBuilder(["test", "test1"])

def js4 = new JsonBuilder(js3)

println js4.toString()

print:

{"content":["test","test1"]}

and this:

import groovy.json.*

def js3 = new JsonBuilder(["test", "test1"])

def js4 = new JsonBuilder(js3.content)

println js4.toString()

prints this (?) :

["test","test1"]

The short answer is that JsonBuilder has a member named content, which represents the payload. When one JsonBuilder absorbs another, we want to replace the payload, and not nest it. This line is the way to replace the payload:

def js4 = new JsonBuilder(js3.content)

Ultimately, this stems from the fact that JsonBuilder.toString() (code here) calls JsonOutput.toJson(object) (code here).

An exercise for the reader is to experiment with:

class MyBuilder {

def content

}

def myB = new MyBuilder(content: ["test", "test1"])

println JsonOutput.toJson(myB)

println JsonOutput.toJson(myB.content)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值