简体   繁体   中英

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

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

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-

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM