5

I am working on Json Objects in java!. I have 2 json objects as follows:

{"a":{"num1":5},"b":{"num1":8}}

{"a":{"num2":7},"b":{"num2":9}}

I want to create a single json object as:

 {"a":{"num1":5,"num2":7},"b":{"num1":8,"num2":9}}

How should i merge the 2 objects to achieve the above result?

2

2 Answers 2

1

The easy way is to create list and loop over two Objects:

public static void main(String[] args) {
    String str1 = "{\"a\":{\"num1\":5},\"b\":{\"num1\":8}}";
    String str2 = "{\"a\":{\"num2\":7},\"b\":{\"num2\":9}}";

    try {
        JSONObject str1Json  = new JSONObject(str1);
        JSONObject str2Json  = new JSONObject(str2);

        List<JSONObject> list = Arrays.asList(str1Json, str2Json);

        JSONObject storage = new JSONObject();
        JSONObject storageA = new JSONObject();
        JSONObject storageB = new JSONObject();
        JSONObject a;
        JSONObject b; 
        JSONObject obj;

        for(int i=1; i<= list.size(); i++){

            obj  = list.get(i-1);

            a = obj.getJSONObject("a");
            b = obj.getJSONObject("b");

            storageA.put("num"+i, a.getInt("num"+i)); // we don't want build list               
            storageB.put("num"+i, b.getInt("num"+i));               
        }

        storage.put("a", storageA);
        storage.put("b", storageB);

        System.out.println(storage.toString());
    } catch (JSONException e1) {
    }
} 

Output:

 {"b":{"num2":9,"num1":8},"a":{"num2":7,"num1":5}}
Sign up to request clarification or add additional context in comments.

Comments

0

Convert the JSON objects into dictionaries using [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; and then perform the manipulations with ease.

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.