What is the best way to combine (merge) 2 JSONObjects?

后端 未结 5 1404
梦毁少年i
梦毁少年i 2021-02-19 02:14

What is the best way to combine (merge) two JSONObjects?

JSONObject o1 = {
    \"one\": \"1\",
    \"two\": \"2\",
    \"three\": \"3\"
}
JSONObject         


        
5条回答
  •  梦如初夏
    2021-02-19 03:01

    json objects to be merge in that new json object like this.

        JSONObject jObj = new JSONObject();
        jObj.put("one", "1");
        jObj.put("two", "2");
        JSONObject jObj2 = new JSONObject();
        jObj2.put("three", "3");
        jObj2.put("four", "4");
    
    
        JSONParser p = new JSONParser();
        net.minidev.json.JSONObject o1 = (net.minidev.json.JSONObject) p
                            .parse(jObj.toString());
        net.minidev.json.JSONObject o2 = (net.minidev.json.JSONObject) p
                            .parse(jObj2.toString());
    
        o1.merge(o2);
    
        Log.print(o1.toJSONString());
    

    now o1 will be the merged json object. you will get the output like this ::

    {"three":"3","two":"2","four":"4","one":"1"}
    

    please refer this link and download the smartjson library ..here is the link http://code.google.com/p/json-smart/wiki/MergeSample

    hope it will help.

提交回复
热议问题