我有一个简单的 JSON 数组。
{
"food" : [
{
"name" : "apple"
},
{
"name" : "orange"
},
{
"name" : "peach"
},
{
"name" : "carrot"
},
{
"name" : "lettuce"
}
]
}
但是当我尝试删除所有内容但保留一个时,删除 for 循环会抢先退出。
String itemToKeepsName = "carrot";
JSONArray list = wrappedFood.getJSONArray("food");
JSONObject addThisItemBack = null; // be ready to make a new space in memory.
println("number of items in list: " + list.length()); // prints 5.
int found = -1;
for(int i = 0; i < list.length(); ++i) {
if(addThisItemBack.equals(list.getJSONObject(i).getString("name"))) {
found = i;
addThisItemBack = new JSONObject(list.getJSONObject(i).toString());
}
}
if (found >= 0) { // found at index 3.
println("number of items before removeall loop: " + list.length()); // prints 5.
for (int i = 0; i < list.length(); ++i) {
println("removed item: " + i); // prints 0, 1, 2.
list.remove(i);
}
println("adding item: " + addThisItemBack); // {"food":["name":"carrot"}]}
list.put(addThisItemBack);
}
但这会导致:
{
"food" : [
{
"name" : "carrot"
},
{
"name" : "lettuce"
}
]
}
而不是:
{
"food" : [
{
"name" : "carrot"
}
]
}
在重新添加项目之前,如何确保列表已完全清空?我是否忽略了一些显而易见的事情?这对 JSON 操作来说是深奥的吗?
最佳答案
每次删除一个元素,列表
就会缩小。这个
for (int i = 0; i < list.length(); ++i) {
println("removed item: " + i); // prints 0, 1, 2.
list.remove(i);
}
表示i
快速传递列表
的长度。我建议List.clear()
喜欢
list.clear();
或带有remove()
的迭代器
Iterator<JsonValue.ValueType> iter = list.iterator();
while (iter.hasNext()) {
JsonValue.ValueType value = iter.next();
println("removed: " + value);
iter.remove();
}
请注意链接的 Javadoc 中的注释:如果在迭代过程中以调用此方法以外的任何方式修改基础集合,则迭代器的行为是未指定的。
关于java - 为什么在删除 JSON 对象时此循环会过早退出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60470218/