Atul Bhardwaj Atul Bhardwaj - 3 months ago 20
JSON Question

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

Answer

Android JSONArray is not meant as a general-purpuse data structure, but to (de)serialize data to and from JSON. Therefore, you should do all add/remove/mutate operations on a java.util.List or something and only if you want to send it over the wire convert to a JSONArray.

Java EE 7 also has a JsonArray class, in their API description they make abundantly clear that they want to prevent people from using it as a replacement for a java.util.list: JsonArray instances are list objects that provide read-only access to the values in the JSON array. Any attempt to modify the list, whether directly or using its collection views, results in an UnsupportedOperationException.

See also this answer

Comments