1 回答
TA贡献1801条经验 获得超8个赞
不要删除数组item。object.id删除它index。您需要遍历数组,找到JSON Object位置number = object.id并将其删除。例子:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.File;
public class JsonApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
ObjectMapper mapper = new ObjectMapper();
ObjectNode root = (ObjectNode) mapper.readTree(jsonFile);
ArrayNode array = (ArrayNode) root.get("secondArray");
int numberToRemove = 1;
for (int i = 0; i < array.size(); i++) {
if (array.get(i).get("number").asInt() == numberToRemove) {
array.remove(i);
break;
}
}
System.out.println(array);
System.out.println(root);
}
}
上面的代码打印:
[{"number":2,"data":"DATA4"}]
{"firstArray":[{"data1":1,"data2":"DATA"},{"data1":2,"data2":"DATA2"}],"secondArray":[{"number":2,"data":"DATA4"}]}
添加回答
举报