json - 在Groovy中使用jsonbuilder修改json

标签 json groovy jsonbuilder

我正在尝试修改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",
.
.
}

有人可以帮助您了解我在做什么错以及如何纠正它。

最佳答案

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

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

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

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

关于json - 在Groovy中使用jsonbuilder修改json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25748170/

相关文章:

PHP - 通过 file_get_contents 发布 JSON

groovy - JMockit - 期望中的模拟方法不返回结果

json - Groovy JsonBuilder 在 toString() 时的奇怪行为

grails - 在Grails中具有嵌套数组的Groovy JSONBuilder

javascript - 消失/重新出现的 JSON 数据

javascript - 根据其他输入填充输入

java - Grails json 使用列表

elasticsearch - 内联脚本包含算术的观察者条件失败

json - 在 Groovy 中使用 JSONBuilder 排除空值

c# - 将枚举序列化为从 Azure Function 返回的 JSON 中的字符串