12

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.

1 Answer 1

19

You need to parse incoming data, then modify it with 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())
Sign up to request clarification or add additional context in comments.

12 Comments

Thanks! Whatever that means :)
@Opal: I didn't know about toPrettyString() before :)
Ah... you're right - so I'll vote up the question too ;)
Excellent so .content is the key here to modify this json.
@NaveenKumarNamachivayam builder.content refers to this method - correct, it has nothing to do with var content.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.