我正在处理一个项目,其中需要清除JSON数组中的所有数据。似乎没有像 jsonArray.clear() 这样的方法。我也尝试了 jsonArray = new JSONArray() 。但这也没用。请给予建议。
只需创建一个新的JSONArray即可。
JSONArray otherJsonArray = new JSONArray();
或者遍历数组并remove(int index)
所需的索引。
http://www.json.org/javadoc/org/json/JSONArray.html#remove(int)
remove
方法?这并不奇怪,因为它不是静态的。它是一个实例方法,应该是jsonArray.remove()
;除非你没有使用相同的org.json.JSONArray对象? - Anew只需输入 jsonArray = new JSONArray()
即可。
创建一个新的对象是可行的,除非您已将其作为参数传递给方法,在这种情况下,您需要修改所引用的对象,因为调用方法不会看到新的引用。
如果是这种情况,请反向操作,这样您就不会超出迭代器范围:
int startingLength = someJsonArray.length();
for (int i = startingLength - 1; i >= 0; i--) {
someJsonArray.remove(i);
}
JSONArray otherJsonArray = new JSONArray("[]");
我有这样一种情况,我想从一个JSONObject中的键为“Constants”的所有条目中删除它们,并创建一个新的JSONArray并将其分配给该键。但是,这样做并不能清除JSONArray,我必须遍历JSONArray并在每个元素上执行jsonArray.remove(i)操作,但是还有第二种方法可以实现,即完全从JSONObject中删除数组元素,在这种情况下是“Constants”,然后重新添加它作为新的JSONArray。
以下是代码示例,使用新数组进行赋值,但不起作用,JSONArray保持不变:(我尝试了上面两种建议,即new JSONArray();和new JSONArray("[]");)
JSONObject jsonObj = new JSONObject(metadataOriginalJSON);
if (jsonObj.isJSONArray("Constants")) {
JSONArray constantsArray = jsonObj.getJSONArray("Constants");
constantsArray = new JSONArray();
metadataConstantsRemoved = jsonObj.toString();
}
这是遍历JSONArray的代码,它可以正常工作:
JSONObject jsonObj = new JSONObject(metadataOriginalJSON);
if (jsonObj.isJSONArray("Constants")) {
JSONArray constantsArray = jsonObj.getJSONArray("Constants");
int i = 0;
int arrayLenSanityCheckPreventEndlessLoop = constantsArray.length();
while (constantsArray.length() > 0 && i < arrayLenSanityCheckPreventEndlessLoop) {
constantsArray.remove(0);
i++;
}
metadataConstantsRemoved = jsonObj.toString();
}
第二种方法是通过删除整个JSONArray元素并将其重新添加到JSONObject中来实现的:
JSONObject jsonObj = new JSONObject(metadataOriginalJSON);
if (jsonObj.isJSONArray("Constants")) {
jsonObj.remove("Constants");
jsonObj.put("Constants", new JSONArray());
metadataConstantsRemoved = jsonObj.toString();
}