这是在Java中合并两个JSONObject(org.json)对象的最佳方法

时间:2018-08-07 11:09:42

标签: java

需要知道如何合并这两个对象

{"a":"1",
 "b":"2"
}

{"c":"4",
 "d":[{}]
}

给予 {a,b,c,d}及其值

1 个答案:

答案 0 :(得分:1)

public static void main(String...strings) throws JSONException {
        String s1 = "{\"a\":\"1\",\"b\":\"2\"}";
        String s2 = "{\"c\":\"4\",\"d\":[{}]}";

        JSONObject jsonObject1 = new JSONObject(s1);
        JSONObject jsonObject2 = new JSONObject(s2);

        Iterator itr = jsonObject2.keys();

        while(itr.hasNext()) {
            String key = (String) itr.next();
            jsonObject1.put(key, jsonObject2.get(key));
        }

        System.out.println(jsonObject1.toString());

    }

输出:{“ a”:“ 1”,“ b”:“ 2”,“ c”:“ 4”,“ d”:[{}]}

另一种假设您具有示例中所示的简单JSON数据

public static void main(String...strings) throws JSONException {
        String s1 = "{\"a\":\"1\",\"b\":\"2\"}";
        String s2 = "{\"c\":\"4\",\"d\":[{}]}";

        int firstIndex = s2.indexOf("{");
        int lastIndex = s1.lastIndexOf("}");

        String result = s1.substring(0, lastIndex)+"," + s2.substring(firstIndex+1);        
        System.out.println(result);

        JSONObject jsonObject = new JSONObject(result);

        Iterator iterator = jsonObject.keys();
        while (iterator.hasNext()) {
            String key = (String) iterator.next();
            System.out.println("Key :: "+key+" value :: "+jsonObject.get(key));         
        }       
    }
  

输出:: {“ a”:“ 1”,“ b”:“ 2”,“ c”:“ 4”,“ d”:[{}]}键::值:: 1键   :: b值:: 2键:: c值:: 4键:: d值:: [{}]