'Unable to create same parameter value twice in json array

In this code, I am trying to creating something like this-

 public String KLYA_JSON_LookUp_MultiNode(String KLYA_To,String KLYA_DLRURL,String KLYA_To2) {
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("dlrurl", KLYA_DLRURL);
        JSONArray array = new JSONArray();
        JSONObject Array_item = new JSONObject();
        Array_item.put("to", KLYA_To);
        Array_item.put("to", KLYA_To2);
        array.add(Array_item);
        jsonObj.put("lookup", array);

        CreatedJson = jsonObj.toString();
        System.out.println(CreatedJson);
        return CreatedJson ;
    }

Output:

{"lookup": [{
"to": "890XXXXXXX"
}, {
"to": "890XXXXXXX"
}], "dlrurl": "http://www.example.com/dlr.php/......"
}

but I dont get as per the above comment, it ends up printing only one to in the array where as it should print two.



Solution 1:[1]

So after Thomas and Petter's suggestion, I worked on it and this is how it got resolved.

JSONObject jsonObj = new JSONObject();
JSONArray array = new JSONArray();
JSONObject Array_item = new JSONObject();
JSONObject NextArray_item = new JSONObject();
jsonObj.put("dlrurl", "url");
NextArray_item.put("to","XXXX");
Array_item.put("to", "XXX");
array.add(Array_item);
array.add(NextArray_item);
jsonObj.put("lookup", array);
CreatedJson = jsonObj.toString();
System.out.println(CreatedJson);

Solution 2:[2]

Insert

array.add(Array_item);
Array_item = new JSONObject();

between the two calls to Array_item.put.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Petter Hesselberg
Solution 2