如何删除JSON对象?我正在使用 Jackson API 2.6.3
我的 JSON 字符串示例
{
"movieList":[
{
"movieID":1,
"title":"TITLE 1",
"type":"DIGITAL",
"status":"COMING SOON",
"synopsis":null,
"director":null,
"mRating":"G",
"casts":null,
"showTimes":[
{
"date":"01/12/15",
"time":"22:00"
},
{
"date":"01/12/15",
"time":"23:30"
}
]
}
]
}
我希望能够删除给定索引的整个 showTimes 对象。
类似于 showtimesList.get(index).remove()
如果它是 arrayList 中的最后一个对象,则该值应设置为 null
.
正如其中一个答案所建议的,我正在转换 JAVA 对象 ShowTime
通过 so 到 JSONNode
ObjectMapper objectMapper = new ObjectMapper();
JsonNode showTimesNode = objectMapper.convertValue(movieList.get(index).getShowTimes(), JsonNode.class);
Iterator<JsonNode> itr = showTimesNode.iterator();
int counter = 1;
while(itr.hasNext() && counter<=showTimeChoice){
if(counter==showTimeChoice){
itr.remove();
Cineplex.updateDatabase(cineplexList);
System.out.println("Sucessfully removed!");
break;
}
counter++;
}
但它抛出错误 Exception in thread "main" java.lang.IllegalStateException
at java.util.ArrayList$Itr.remove(Unknown Source)
当我试图删除 showTimes
的第二个元素时在上面给定的 JSON 字符串上
这是
{
"date":"01/12/15",
"time":"23:30"
}
最佳答案
for (JsonNode personNode : rootNode) {
if (personNode instanceof ObjectNode) {
if (personNode.has("showTimes")) {
ObjectNode object = (ObjectNode) personNode;
object.remove("showTimes");
}
}
}
关于java - 删除 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33605452/