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

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

问题描述

是否可以将两个 JSON 文档与 Jackson JSON 库合并?我基本上使用带有简单 Java 地图的 Jackson 映射器.

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

我尝试在 Google 和 Jackson 的文档中进行搜索,但找不到任何内容.

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天全站免登陆