使用Jackson合并两个JSON文档 [英] Merging Two JSON Documents Using Jackson

查看:1728
本文介绍了使用Jackson合并两个JSON文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将两个JSON文档与Jackson JSON库合并?我基本上使用Jackson mapper和简单的Java Maps。

Is it possible to merge two JSON documents with the Jackson JSON library? I am basically using the Jackson mapper with simple Java Maps.

我试图在谷歌和杰克逊的文档中搜索但找不到任何东西。

I've tried to search in Google and Jackson's documentation but couldn't find anything.

推荐答案

一种方法是使用 ObjectReader ,如下所示:

One way is to use ObjectReader like so:

MyBean defaults = objectMapper.readValue(defaultJson, MyBean.class);
ObjectReader updater = objectMapper.readerForUpdating(defaults);
MyBean merged = updater.readValue(overridesJson);

这将合并来自两个来源的数据。这只会产生一个浅表副本,即不会对包含的对象进行递归合并。

which will combine data from two sources. This only makes a shallow copy, i.e. does not do recursive merge on contained objects.

否则你可能只需要将JSON读作树( JsonNode ),循环内容并手动合并。这通常是有道理的,因为合并的规则并不是微不足道的,每个人都有自己的合并应该如何运作的想法。

Otherwise you may need to just read JSON as a tree (JsonNode), loop over contents and merge manually. This often makes sense anyway since rules of merging are not trivial, and everyone has their own ideas of how merging should work.

编辑 :( 2017年4月3日)

EDIT: (03-Apr-2017)

根据@Fernando Correia的评论,实际上有一个新的功能在即将推出的Jackson 2.9(将于2017年4月或5月发布)中添加,最终允许深度合并。

As per @Fernando Correia's comment, there is actually a new feature added in upcoming Jackson 2.9 (to be released in April or May 2017) that does allow deep merging, finally.

这篇关于使用Jackson合并两个JSON文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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