Combine two Json objects in java

1

I have two JSONObjects with the same structure, but I want to combine them so that the characteristics are kept in common and that those that are different give priority to the second object.

Example:

JSONObject obj1 = new JSONObject("{
"name":"manu",
"age":23,
"occupation":"SE"
}")

JSONObject obj2 = new JSONObject("{
"name":"manu",
"age":23,
"country":"india",
"email" : "[email protected]"
}")

Expected:

JSONObject result = {
"name":"manu",
"age":23,
"occupation":"SE",
"country":"india",
"email" : "[email protected]"
}

I tried the following:

        JSONObject obj1 = new JSONObject("{\n"
                + "\"name\":\"manu\",\n"
                + "\"age\":23,\n"
                + "\"occupation\":\"SE\"\n"
                + "}");

        JSONObject obj2 = new JSONObject("{\n"
                + "\"name\":\"manu\",\n"
                + "\"age\":23,\n"
                + "\"country\":\"india\"\n"
                + "}");

        JSONObject result = new JSONObject(obj2.toString());

        Iterator<?> keys = obj1.keys();

        while (keys.hasNext()) {
            String key = (String) keys.next();
            if (!result.has(key))
                result.put(key, obj1.get(key));
        }

But I do not consider it efficient, because I will use it for very large Jsons

    
asked by gibran alexis moreno zuñiga 15.12.2017 в 22:32
source

1 answer

1

I think you are using the best available solution. There are libraries that provide methods to "merge" json objects, but if you inspect their source code, they do exactly what you are doing (create an iterator and traverse the elements of one object to insert them into another). So I think it's more efficient to do it yourself with your code than to load a complete library to use the same function.

    
answered by 16.12.2017 / 23:06
source