0

My JsonArray structure is like this:

resultArray = 
[
{
    "key1": [],
    "key2": "keyval",
    "key3": "keyVal"
},
{
    "key1": [],
    "key2": "keyval",
    "key3": "keyVal"
},
{
    "key1": [],
    "key2": "keyval",
    "key3": "keyVal"
}
]

I am trying add JsonObject at 1st postion.

JSONObject jo = new JSONObject();
jo.put("aa","bb");

( (JSONObject)resultArray.get(0)).getJSONArray("key1").put(jo);

after executing the above step below is the result.

resultArray = [{ "key1": [{"aa","bb"}] ,"key2":"keyval", "key3":"keyVal" },
{ "key1": [{"aa","bb"}] ,"key2":"keyval", "key3":"keyVal" },
{ "key1": [{"aa","bb"}] ,"key2":"keyval", "key3":"keyVal" } ]

Values are getting added to the all the Items in my JsonArray.

But I want to add to the specific position.

In above case , I want to add to only at '0' position.

Please let me know if ther's any mistake in below line:

( (JSONObject)resultArray.get(0)).getJSONArray("key1").put(jo);
The Heist
  • 1,444
  • 1
  • 16
  • 32
brig
  • 3,721
  • 12
  • 43
  • 61

1 Answers1

0

Hi I tried your code and works fine. For more clarification Please check with working example.

try {
        JSONArray resultArray = new JSONArray();

        JSONObject obj1 = new JSONObject();
        JSONArray keyArray1 = new JSONArray();
        obj1.put("key1", keyArray1);
        resultArray.put(obj1);

        JSONObject obj2 = new JSONObject();
        JSONArray keyArray2 = new JSONArray();
        JSONObject item1 = new JSONObject();
        item1.put("value", "old");
        keyArray2.put(item1);
        obj2.put("key1", keyArray2);
        resultArray.put(obj2);

        JSONObject jo = new JSONObject();
        jo.put("value", "new");

        Log.i("@@@@",
                "before Add  lengths "
                        + ((JSONObject) resultArray.get(0)).getJSONArray(
                                "key1").length());
        ((JSONObject) resultArray.get(0)).getJSONArray("key1").put(jo);
        Log.i("@@@@",
                "After Add resultArray [0] "
                        + ((JSONObject) resultArray.get(0))
                                .getJSONArray("key1").get(0).toString());
        Log.i("@@@@",
                "After Add resultArray [1] "
                        + ((JSONObject) resultArray.get(1))
                                .getJSONArray("key1").get(0).toString());
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Run this and see the result in LogCat.

Result:

04-06 12:38:03.295: I/@@@@(10307): before Add lengths 0

04-06 12:38:03.295: I/@@@@(10307): After Add resultArray [0] {"value":"new"}

04-06 12:38:03.295: I/@@@@(10307): After Add resultArray [1] {"value":"old"}

Prakash M
  • 651
  • 3
  • 13