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
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.
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.
We can merge two JSON arrays using the addAll() method (inherited from interface java. util.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With