如何在groovy中修改JSON [英] How to modify JSON in groovy

查看:877
本文介绍了如何在groovy中修改JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用JsonBuilder来构建JSONObject / String。

但是,如何更新/更改此JSONObject / String中一个字段的值?



我没有看到使用JsonBuilder做这件事的可能性。那么我使用什么?

JsonBuilder,那么你可以这样做:
$ b

  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}]}'

但是由于 content 没有从对象中显式导出,所以我称之为副作用,并且不会依赖它在未来版本的Groovy中工作。



在将它传递给 JsonBuilder 之前,更好地获取您的地图,或者如果这不可行我想你会需要使用 JsonSlurper 修改生成的Map,然后用<$重建Json字符串来解析Json字符串c $ c> JsonBuilder 再次。


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?

解决方案

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.

这篇关于如何在groovy中修改JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆