Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert object to specific position in jsonarray

I want to add an object to a specific position in JSonArray. My Current JsonArray look like this

{
    "imgs": [
        "String1",
        "String2",
        "String3",
        "String4"
    ]
}

I need to insert one more item in jsonarray at 1st position like this-

jsonArray.put(1,"String5")

this is replacing item at first position But I need below result

{
    "imgs": [
        "String1",
        "String5",
        "String2",
        "String3",
        "String4"
    ]
}

Please suggest

like image 201
Atul Bhardwaj Avatar asked Jan 11 '16 09:01

Atul Bhardwaj


People also ask

What is the difference between JSONArray and JSONObject?

JSONObject and JSONArray are the two common classes usually available in most of the JSON processing libraries. A JSONObject stores unordered key-value pairs, much like a Java Map implementation. A JSONArray, on the other hand, is an ordered sequence of values much like a List or a Vector in Java.

How do I check if an object is JSONArray or JSONObject?

You can check the character at the first position of the String (after trimming away whitespace, as it is allowed in valid JSON). If it is a { , you are dealing with a JSONObject , if it is a [ , you are dealing with a JSONArray . If you are dealing with JSON (an Object ), then you can do an instanceof check.

How add JSON array to another JSON array in Java?

We can merge two JSON arrays using the addAll() method (inherited from interface java. util.

What is JSONObject put?

JSONObject. put(String key, java.util.Collection value) Put a key/value pair in the JSONObject, where the value will be a JSONArray which is produced from a Collection.


1 Answers

Seem too old but you can do like this:

public void addToPos(int pos, JSONObject jsonObj, JSONArray jsonArr){
   for (int i = jsonArr.length(); i > pos; i--){
      jsonArr.put(i, jsonArr.get(i-1));
   }
   jsonArr.put(pos, jsonObj);
}
like image 171
hungps Avatar answered Sep 21 '22 10:09

hungps