0

I have these two JsonObject which uses javax.json. How can i merge these three and have as one Jason Object or JsonArray. Please not that I tried JASONObject and it didnt work as it is org. lib.

JsonObject jo = Json.createObjectBuilder()
 .add("click", Json.createArrayBuilder()
    .add(Json.createObjectBuilder()
       .add("object", "Doe")))
 .build();

JsonObject jo1 = Json.createObjectBuilder()
 .add("open", Json.createArrayBuilder()
    .add(Json.createObjectBuilder()
      .add("page", "Doe")
      .add("ms", "5000")))
 .build();

JsonObject jo2 = Json.createObjectBuilder()
 .add("open", Json.createArrayBuilder()
    .add(Json.createObjectBuilder()
      .add("page", "Doe")
      .add("ms", "5000")))
 .build();
2
  • add to gather and have as one object Commented Sep 25, 2014 at 12:13
  • Yes, but how? As a single large JSON object, or a JSON array containing JSON objects, or as a JSON object containing JSON objects?? Commented Sep 25, 2014 at 12:16

3 Answers 3

2

Instead of writing org.json library, I ended up writing a utility method of my own as below

Reference : Merge 2 javax.json.JsonObject

private JsonObject mergeProfileSummary(JsonObject oldJsonObject, JsonObject newJsonObject) {
        JsonObjectBuilder jsonObjectBuilder =Json.createObjectBuilder();

        for (String key : oldJsonObject.keySet()){
            jsonObjectBuilder.add(key, oldJsonObject.get(key));
        }
        for (String key : newJsonObject.keySet()){
            jsonObjectBuilder.add(key, newJsonObject.get(key));
        }

        return jsonObjectBuilder.build();
    }
Sign up to request clarification or add additional context in comments.

Comments

1

Try this,

JSONObject mergeJson = new JSONObject();
mergeJson.putAll(jo1);
mergeJson.putAll(jo2);
mergeJson.putAll(jo3);

2 Comments

This is org.json format. I already tried this and it didn't work. But thanks lot for stopping by
This answer should be edited to follow the javax.JsonObject instead of org.json as the function calls for org.json is the same as javax.JsonObject and OP didn't ask for org.json.
1

I changed the creating JASONObject part by using org.json lib and it worked;

JSONObject jo = new JSONObject();
jo.put("page", "some val");
jo.put("ms", time);
JSONObject finalObj = new JSONObject();
finalObj.put("open", jo);

JSONObject jo1 = new JSONObject();
jo.put("object", ele.getAttributes().getNamedItem("seleniumwebdriver").getNodeValue());
JSONObject finalObj = new JSONObject();                                 
finalObj.put("click", jo);

And here is the code for merging:

JSONObject finalArr = new JSONObject();
finalJsonArr.add(jo);
finalJsonArr.add(jo1);

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.