且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Groovy中将新的json字段添加到现有的json

更新时间:2023-12-02 23:27:22

您可以使用 LazyMap ,您只需向其中添加新条目(添加println作为提示的行):

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控制台上尝试