gpt4 book ai didi

json - 将 json 附加到 groovy 中的 json

转载 作者:行者123 更新时间:2023-12-02 00:57:30 24 4
gpt4 key购买 nike

我是 groovy 的新手。我的要求是我必须将一个 json 附加到一个 json 中。我的代码如下:

我构造的JSON:

def builder = new groovy.json.JsonBuilder()
def root=builder.event{
type "model_output_load_init"
time new Timestamp(date.getTime())
status "success"
}

来自数据库的 JSON:

def json = rs.getString("status");

现在我必须将构造附加到来自数据库的 JSON 中。请帮我解决这个问题。提前致谢。

编辑:

我构造的 JSON:

{
"event": {
"type": "model_output_load_init",
"time": "2015-10-01T14:08:17+0000",
"status": "success"
}
}

来自数据库的 JSON:

{
"model_build": {
"Initialized": {
"Timestamp": ""
}
},
"modelExec": {
"Initialized": {
"Timestamp": ""
}
}
}

需要的输出:

{
"model_build": {
"Initialized": {
"Timestamp": ""
}
},
"modelExec": {
"Initialized": {
"Timestamp": ""
}
},
"event": {
"type": "model_output_load_init",
"time": "2015-10-01T14:08:17+0000",
"status": "success"
}

}

最佳答案

您可以附加到 JsonSlurper 生成的 map 。

import groovy.json.JsonBuilder
import groovy.json.JsonSlurper

def builder = new JsonBuilder()
def root = builder.event{
type "model_output_load_init"
time new Timestamp(date.getTime())
status "success"
}

// Simulates the JSON from DB
def json = new JsonSlurper().parseText('''
{
"model_build": {
"Initialized": {
"Timestamp": ""
}
},
"modelExec": {
"Initialized": {
"Timestamp": ""
}
}
}''')

// Append the built JSON to the "slurped" JSON
json.event = root.event

// Re-build the JSON so it can saved as a String
new JsonBuilder(json).toPrettyString()

输出看起来像这样:

{
"event": {
"type": "model_output_load_init",
"time": "2015-10-01T14:39:11+0000",
"status": "success"
},
"modelExec": {
"Initialized": {
"Timestamp": ""
}
},
"model_build": {
"Initialized": {
"Timestamp": ""
}
}
}

关于json - 将 json 附加到 groovy 中的 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32889997/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com