3

I use JsonBuilder to build a JSONObject/String.

But, how can I update/change value of one field in this JSONObject/String?

I am not seeing the possibility of doing this using JsonBuilder. What show I use then?

Jason Whitehorn
  • 13,585
  • 9
  • 54
  • 68
user1947415
  • 933
  • 4
  • 14
  • 31
  • 1
    [JsonSlurper](http://groovy.codehaus.org/gapi/groovy/json/JsonSlurper.html)? – tim_yates Nov 20 '13 at 19:25
  • That will only return a map. Do you mean update the map and convert back to json? – user1947415 Nov 20 '13 at 20:32
  • Yes. JsonSlurper to read the json into a map. Change it, and write the modified map back to json with JsonBuilder – tim_yates Nov 20 '13 at 21:02
  • Yes, that will work. But, I prefer changing the JsonBuilder directly. The JsonBuilder return a map itself. but, that map I can only get the first level properties. For complex properties I am not able to get the value. – user1947415 Nov 20 '13 at 21:58
  • So you want to change the property of a map encoded as a Json String without parsing the String? – tim_yates Nov 20 '13 at 22:06
  • Added an answer that shows how to do it, but it's probably better to get your data right before passing it to JsonBuilder if at all possible (for future proofing) – tim_yates Nov 21 '13 at 12:14

1 Answers1

8

If you have to change the content you already put into the JsonBuilder, then you could do:

import groovy.json.*

def map = [ users:[ [ name:'tim', posts:43 ], [ name:'alice', posts:72 ] ] ]

JsonBuilder builder = new JsonBuilder( map )

builder.content.users[ 0 ].name = 'dave'

assert builder.toString() == '{"users":[{"name":"dave","posts":43},{"name":"alice","posts":72}]}'

But as content is not explicitly exported from the Object, I'd call this a side-effect and would not rely on it working in future versions of Groovy.

Better to get your map right before you pass it to JsonBuilder, or if that isn't possible I guess you'll need to parse the Json string with JsonSlurper modify the resulting Map and then rebuild the Json with JsonBuilder again.

tim_yates
  • 167,322
  • 27
  • 342
  • 338