简体   繁体   English

如何添加com.google.gson.JsonArray的特定索引?

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

com.google.gson.JsonArray has add method which will append the element. com.google.gson.JsonArray具有将附加元素的add方法。 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. 我尝试使用这种代码在第0个索引处添加元素。 I am looking for something better without instantiating a new JsonArray . 我正在寻找更好的东西,而无需实例化新的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. 由于JsonArray没有插入方法,这意味着你必须自己创建。 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: 因此,使用此方法,将新项0插入位置0的现有数组[1,2,3]:

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

Without altering the original array, the method will return a new array [0, 1, 2, 3]. 不改变原始数组,该方法将返回一个新数组[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。

JsonElement set(int index, JsonElement element) Replaces the element at the specified position in this array with the specified element. JsonElement set(int index,JsonElement 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- https://static.javadoc.io/com.google.code.gson/gson/2.6.2/com/google/gson/JsonArray.html#set-int-com.google.gson.JsonElement-

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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