在Groovy中生成JSON对象
由于某些原因,我无法使用JSONBuilder在Groovy中创建JSON对象 这是我所拥有的,但它回来了{}:在Groovy中生成JSON对象,groovy,jsonbuilder,Groovy,Jsonbuilder,由于某些原因,我无法使用JSONBuilder在Groovy中创建JSON对象 这是我所拥有的,但它回来了{}: import groovy.json.JsonBuilder JsonBuilder builder = new JsonBuilder() builder { name "Name" description "Description" type "schedule type" schedule {
import groovy.json.JsonBuilder
JsonBuilder builder = new JsonBuilder()
builder {
name "Name"
description "Description"
type "schedule type"
schedule {
recurrenceType "one time"
start "${startDateTime}"
end "${endDateTime}"
}
scope {
entities ["${applicationId}"]
matches [
{
tags [
{
key "key name"
context "some context"
}
]
}
]
}
}
有人知道用嵌套元素创建JSON对象的简单方法吗
检查我倾向于发现
JsonOutput
更易于用于已构造的数据。你的应该是这样的:
groovy.json.JsonOutput.toJson(
[name: "Name",
description: "Description",
type: "schedule type",
schedule: [
recurrenceType: "one time",
start: "${startDateTime}",
end: "${endDateTime}"
],
scope: [
entities: ["${applicationId}"],
matches: [
[
tags: [
[
key: "key name",
context: "some context"
]
]
]
]
]]
)
我倾向于发现
JsonOutput
更易于用于已经构建的数据。你的应该是这样的:
groovy.json.JsonOutput.toJson(
[name: "Name",
description: "Description",
type: "schedule type",
schedule: [
recurrenceType: "one time",
start: "${startDateTime}",
end: "${endDateTime}"
],
scope: [
entities: ["${applicationId}"],
matches: [
[
tags: [
[
key: "key name",
context: "some context"
]
]
]
]
]]
)
为什么不像
groovy.json.JsonOutput.toJson([name:'name',description:'description',schedule:[recurrenceType:'one time']])这样的东西呢?
?参数只是一个包含所有数据的映射。@ernest_k我试过你的建议了。我想在这一点上,我尝试了任何变化:/我的IDE抱怨如果我添加逗号,就像在你的建议中一样,所以我没有添加逗号,但它返回{}你测试过你的建议了吗?对你有用吗?返回JsonOutput.toJson({name:“name”description:“description”…}).toString()您拥有的不是我建议的。我建议使用映射参数([…:…]
,而不是{}
)。是的,我对它进行了测试,它生成了字符串{“name”:“name”,“description”:“description”,“schedule”:{“recurrenceType”:“one time”}
@ernest_k I good one。差不多了。如何处理输出中也需要[]的匹配项和标记?“匹配项”:[{“标记”:[{key”key name“context”some context“}]}]将它们加倍?我将为您添加一个答案。为什么不使用类似groovy.json.JsonOutput.toJson([name:'name',description:'description',schedule:[recurrenceType:'one time']])
?参数只是一个包含所有数据的映射。@ernest_k我试过你的建议了。我想在这一点上,我尝试了任何变化:/我的IDE抱怨如果我添加逗号,就像在你的建议中一样,所以我没有添加逗号,但它返回{}你测试过你的建议了吗?对你有用吗?返回JsonOutput.toJson({name:“name”description:“description”…}).toString()您拥有的不是我建议的。我建议使用映射参数([…:…]
,而不是{}
)。是的,我对它进行了测试,它生成了字符串{“name”:“name”,“description”:“description”,“schedule”:{“recurrenceType”:“one time”}
@ernest_k I good one。差不多了。如何处理输出中也需要[]的匹配项和标记?“匹配项”:[{“标记”:[{key”key name“context”some context“}]}]将它们加倍?我将为您添加一个答案。