繁体   English   中英

将 json 对象与 java 合并

[英]Merge json objects with java

我有两个 JSON 文件。 我想将它们组合成一个,使第二个文件具有更高的优先级。 那是:

  • 如果 1 具有属性foo而 2 没有属性foo ,则 3 将具有属性foo ,其值从 1 开始。
  • 如果 2 具有属性foo而 1 没有属性foo ,则 3 将具有属性foo ,其值来自 2。
  • 如果 1 和 2 都具有属性foo ,则 3 将具有属性foo ,其值来自 2。

我需要在 Java 中执行此操作。 The final JSON object will be deserialized to a Java object with Google Gson.

干得好:

Gson gson = new Gson();
//read both jsons
Map<String, Object> json1 = gson.fromJson("<json1>", Map.class);
Map<String, Object> json2 = gson.fromJson("<json2>", Map.class);
//create combined json with contents of first json
Map<String, Object> combined = new HashMap<>(json1);
//Add the contents of first json. It will overwrite the values of keys are 
//same. e.g. "foo" of json2 will take precedence if both json1 and json2 have "foo" 
combined.putAll(json2);
gson.toJson(combined);

要深度合并具有自定义优先级的 JSON 文件并返回为 Gson,您应该使用confectory-datamapper-gson httpsr/ githubconfector.com/wiki/Downvicload.

你可以这样做:

Configuration<JsonObject> json1 = Configuration.<JsonObject>builder()
                .mapper(new GsonJsonObjectMapper())
                .source("classpath://file1.json")
                .precedence(9) // Higher priority
                .build();

Configuration<JsonObject> json2 = Configuration.<JsonObject>builder()
                .mapper(new GsonJsonObjectMapper())
                .source("classpath://file2.json")
                .precedence(1) // Lower priority
                .build();

JsonObject merged = json1.merge(json2).getBean();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM