在 Groovy 中使用 jsonbuilder 修改 json [英] modifying json with jsonbuilder in Groovy

查看:57
本文介绍了在 Groovy 中使用 jsonbuilder 修改 json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试修改 json 的内容,然后打印它以查看它是否已使用此代码更改但出现错误

I am trying to modify content of json and then print it to see if it has changed with this code but getting error

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

错误:

no such property: device

json 看起来像这样:

json looks like this:

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

有人可以帮助理解我做错了什么以及我该如何纠正它.

can someone help in understanding what am i doing wrong and how can i correct it.

推荐答案

需要解析传入的内容,用JsonBuilder

You need to parse incoming content, the modify it with 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())

这篇关于在 Groovy 中使用 jsonbuilder 修改 json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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