How to modify JSON in groovy

Deadly 提交于 2019-12-11 03:44:55

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/20104819/how-to-modify-json-in-groovy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!