How to add com.google.gson.JsonArray to a specific index?

com.google.gson.JsonArrayAdded a method that will add an item. If I would like to add at a specific index, how to do this?

I tried with this code to add an element to the 0th index. I am looking for something better without creating a new one JsonArray.

JsonArray newArray = new JsonArray();
newArray.add(new JsonPrimitive(3));
for (int i = 0; i < myArray.size(); i++) {
    newArray.add(myArray.get(i));
}
+4
source share
2 answers

I think you are looking for something like this, you can replace the existing JsonElement with a specific index using the method mentioned below.

Set JsonElement (index int, 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-

+1

JsonArray , , . .

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;
}

, , 0 [1, 2, 3] 0:

insert(0, new JsonPrimitive(0), myArray);

[0, 1, 2, 3]. , !

+1

Source: https://habr.com/ru/post/1678091/


All Articles