将json对象与java合并

将json对象与java合并,java,json,Java,Json,我有两个JSON文件。我想将它们合并为一个,这样第二个文件就具有更高的优先级。即: 如果1具有属性foo,而2没有属性foo,则3将具有值为1的属性foo 如果2具有属性foo,而1没有属性foo,则3将具有值为2的属性foo 如果1和2都具有属性foo,则3将具有值为2的属性foo 我需要用Java来做这个。最后一个JSON对象将通过Google Gson反序列化为Java对象。在这里: Gson gson = new Gson(); //read both jsons Map<St

我有两个JSON文件。我想将它们合并为一个,这样第二个文件就具有更高的优先级。即:

  • 如果1具有属性
    foo
    ,而2没有属性
    foo
    ,则3将具有值为1的属性
    foo
  • 如果2具有属性
    foo
    ,而1没有属性
    foo
    ,则3将具有值为2的属性
    foo
  • 如果1和2都具有属性
    foo
    ,则3将具有值为2的属性
    foo
我需要用Java来做这个。最后一个JSON对象将通过Google Gson反序列化为Java对象。

在这里:

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);
Gson-Gson=new-Gson();
//阅读两个JSON
Map json1=gson.fromJson(“,Map.class”);
Map json2=gson.fromJson(“,Map.class”);
//创建包含第一个json内容的组合json
Map combined=newhashmap(json1);
//添加第一个json的内容。它将覆盖密钥的值
//一样。e、 如果json1和json2都有“foo”,则json2的“foo”将优先
联合。putAll(json2);
toJson(合并);
给你:

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);
Gson-Gson=new-Gson();
//阅读两个JSON
Map json1=gson.fromJson(“,Map.class”);
Map json2=gson.fromJson(“,Map.class”);
//创建包含第一个json内容的组合json
Map combined=newhashmap(json1);
//添加第一个json的内容。它将覆盖密钥的值
//一样。e、 如果json1和json2都有“foo”,则json2的“foo”将优先
联合。putAll(json2);
toJson(合并);

欢迎来到StackOverflow!记住要包括你已经尝试过的,以及你知道为什么失败的原因。请参阅欢迎使用StackOverflow!记住要包括你已经尝试过的,以及你知道为什么失败的原因。参考:我认为这与OP想要的相反,但是需要纠正。更正逻辑:)我认为这与OP想要的相反,但是需要纠正。更正逻辑:)