基本上,我想以某种方式从Groovy对象创建一个JSON对象。 Groovy对象具有键值对,其中一个值是Groovy数组:
import groovy.json.*
// Imagine "handler" gets called somehow and an event gets passed to it.
def handler(event) {
def capabilitiesList = event.device.capabilities.findAll { attr -> attr.name != null }
def json = new JsonBuilder({
id event.deviceId
displayName event.displayName
value event.value
})
}
log.debug capabilitiesList
log.debug json.toPrettyString()
此时,json.toPrettyString()
给了我这个:
{
"id": "asdfl469934623sdglsi3aqaq",
"displayName": "Some Lightbulb",
"value": "on"
}
capabilitiesList
给了我这个:
["Test 1", "Test 2", "Test 3"]
如何将capabilitiesList
数组添加到Groovy对象中,以便将其转换为JSON?
我似乎无法得到任何工作;唯一可行的是:
// ...
def json = new JsonBuilder({
id event.deviceId
displayName event.displayName
value event.value
capabilitiesList "Test 1", "Test 2", "Test 3"
})
// ...
这给了我这个(正确的)JSON输出:
{
"id": "asdfl469934623sdglsi3aqaq",
"displayName": "Some Lightbulb",
"value": "on",
"capabilitiesList": ["Test 1", "Test 2", "Test 3"]
}
但这显然没有用,因为它是硬编码的。所以我尝试直接引用数组:
// ...
def capabilitiesList = event.device.capabilities.findAll { attr -> attr.name != null }
def json = new JsonBuilder({
id event.deviceId
displayName event.displayName
value event.value
capabilitiesList capabilitiesList
})
// ...
但是这会以某种方式打破JsonBuilder
,并且它不会输出任何内容。
我可能在这里做了一些非常愚蠢的事情,但我无法弄清楚如何完成这件事。第一次使用Groovy。谢谢你的帮助!
答案 0 :(得分:0)
使用构建器DSL应该可以工作。例如:
List list = ['Test1', 'Test2', 'Test3']
def builder = new groovy.json.JsonBuilder()
builder {
id "asdfl469934623sdglsi3aqaq"
displayName "Some Lightbulb"
value "on"
capabilitiesList list
}
println builder.toPrettyString()
打印
{
"id": "asdfl469934623sdglsi3aqaq",
"displayName": "Some Lightbulb",
"value": "on",
"capabilitiesList": [
"Test1",
"Test2",
"Test3"
]
}