如何在Groovy中将新的json字段添加到现有的json [英] How to add new json field to existing json in groovy

查看:511
本文介绍了如何在Groovy中将新的json字段添加到现有的json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现有的Json如下:

My existing Json looks like:

def json_req = "{\"date\":\"Tue, 06 Oct 2015 09:10:52 GMT\",\"nonce\":\"6cm7PmwDOKs\",\"devId\":\"<value>\",\"appId\":\"<value>\"}

执行操作,我可以获得带有值的sig字段.我需要将此附加字段附加值,如下所示:

Perform the operation I can get sig field with value. I need to append this additional field with value as below:

"sig":"<value>"

因此新的json看起来像:

So that the new json looks like:

def json_req = "{\"date\":\"Tue, 06 Oct 2015 09:10:52 GMT\",\"nonce\":\"6cm7PmwDOKs\",\"devId\":\"<value>\",\"appId\":\"<value>\",\"sig\":\"<value>\"}"

我可以在同一脚本中将此新参数附加到json中的值吗?

Within the same script can I append this new parameter with the value in json?

推荐答案

您可以使用

You can parse the json with JsonSlurper, and since the result of that is a LazyMap, you can simply add the new entry to it (lines with println added as hints):

import groovy.json.*

def json_req = '''{
"date":"Tue, 06 Oct 2015 09:10:52 GMT", 
"nonce":"6cm7PmwDOKs",
"devId":"<value>",
"appId": "<value>"
}'''

def json = new JsonSlurper().parseText(json_req)
println json.getClass().getName()
json << [sig: "<value>"] // json.put('sig', '<value>')
println JsonOutput.toJson(json)

groovy Web控制台上尝试

这篇关于如何在Groovy中将新的json字段添加到现有的json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆