com.google.gson.JsonArray
has add method which will append the element. If I would like to add at specific index, how to do that?
I tried with this kind of code to add element at 0th index. I am looking for something better without instantiating a new JsonArray
.
JsonArray newArray = new JsonArray();
newArray.add(new JsonPrimitive(3));
for (int i = 0; i < myArray.size(); i++) {
newArray.add(myArray.get(i));
}
We can also add a JSONArray to JSONObject. We need to add a few items to an ArrayList first and pass this list to the put() method of JSONArray class and finally add this array to JSONObject using the put() method.
1) Create a Maven project and add json dependency in POM. xml file. 2) Create a string of JSON data which we convert into JSON object to manipulate its data. 3) After that, we get the JSON Array from the JSON Object using getJSONArray() method and store it into a variable of type JSONArray.
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.
We can merge two JSON arrays using the addAll() method (inherited from interface java. util.
Since there is no insert method for JsonArray, it means you have to make your own. It inserts a single item in the array at the point of your choosing.
public static JsonArray insert(int index, JsonElement val, JsonArray currentArray) {
JsonArray newArray = new JsonArray();
for (int i = 0; i < index; i++) {
newArray.add(currentArray.get(i));
}
newArray.add(val);
for (int i = index; i < currentArray.size(); i++) {
newArray.add(currentArray.get(i));
}
return newArray;
}
So using this method, to insert a new item 0 into an existing array [1, 2, 3] at position 0:
insert(0, new JsonPrimitive(0), myArray);
Without altering the original array, the method will return a new array [0, 1, 2, 3]. Hope that helps!
I think you are looking for something like this, you can replace an existing JsonElement at a particular index using the method mentioned below.
JsonElement set(int index, JsonElement element) Replaces the element at the specified position in this array with the specified element.
For reference:
https://static.javadoc.io/com.google.code.gson/gson/2.6.2/com/google/gson/JsonArray.html#set-int-com.google.gson.JsonElement-
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