Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

modifying json with jsonbuilder in Groovy

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())

error:

no such property: device

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.

like image 500
user1207289 Avatar asked Sep 09 '14 15:09

user1207289


1 Answers

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())
like image 130
Opal Avatar answered Oct 05 '22 20:10

Opal