0

I have two JSON files. I want to combine them into one in such a way that the second file has a greater priority. That is:

  • if 1 has the property foo and 2 has no property foo, 3 will have the property foo with the value from 1.
  • if 2 has the property foo and 1 has no property foo, 3 will have the property foo with the value from 2.
  • if 1 and 2 both have the property foo, 3 will have the property foo with the value from 2.

I need to do this in Java. The final JSON object will be deserialized to a Java object with Google Gson.

1
  • Welcome to StackOverflow! Remember to include what you've tried and what you know about why it didn't work. Refer to stackoverflow.com/help/mcve Commented Mar 4, 2016 at 0:56

2 Answers 2

3

Here you go:

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);
Sign up to request clarification or add additional context in comments.

2 Comments

I think this is the reverse of what the OP wanted, but is trivial to correct.
Corrected the logic :)
0

To deep-merge JSON files with custom priorities and return as Gson, you should use confectory-datamapper-gson https://github.com/oswaldobapvicjr/confectory/wiki/Download.

Here's how you could do it:

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.