根据java中的键添加2个json对象

时间:2013-12-13 10:24:15

标签: java json merge

我正在研究java中的Json Objects!我有2个json对象如下:

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

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

我想创建一个单独的json对象:

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

如何合并2个对象以达到上述效果?

2 个答案:

答案 0 :(得分:1)

简单的方法是创建列表并循环遍历两个对象:

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) {
    }
} 

输出:

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

答案 1 :(得分:0)

使用[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];将JSON对象转换为字典,然后轻松执行操作。