在Groovy中使用jsonbuilder修改json

rdlzhqv9  于 2023-10-15  发布在  其他
关注(0)|答案(1)|浏览(138)

我试图修改json的内容,然后打印出来,看看它是否与此代码发生了变化,但得到错误

def builder = new JsonBuilder(request)
 log.info(builder.content)
 builder.content.device.dpidsha1= 'abcd'  
 log.info(builder.toPrettyString())

错误类型:

no such property: device

json看起来像这样:

{
   "app":{ },
   "at":2,
   "badv":[ ],
   "bcat":[ ],
   "device":{
      "carrier":"310-410",
      "connectiontype":3,
      "devicetype":1,
      "dnt":0,
      "dpidmd5":"268d403db34e32c45869bb1401247af9",
      "dpidsha1":"1234",
.
.
}

有人能帮助我理解我做错了什么,我该如何纠正它。

htzpubme

htzpubme1#

您需要解析传入的数据,然后使用JsonBuilder对其进行修改

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

def data = """
{
   "app":{ },
   "at":2,
   "badv":[ ],
   "bcat":[ ],
   "device":{
      "carrier":"310-410",
      "connectiontype":3,
      "devicetype":1,
      "dnt":0,
      "dpidmd5":"268d403db34e32c45869bb1401247af9",
      "dpidsha1":"1234" 
   }
}"""

def slurped = new JsonSlurper().parseText(data)
def builder = new JsonBuilder(slurped)
builder.content.device.dpidsha1 = 'abcd'  
println(builder.toPrettyString())

相关问题