在Groovy中使用jsonbuilder修改json

时间:2014-09-09 15:14:09

标签: 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",
.
.
}

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

1 个答案:

答案 0 :(得分:10)

您需要解析传入的内容,并使用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())