删除JSON对象的元素

3

我如何删除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转换为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++;
}

但是当我尝试从给定的JSON字符串中删除showTimes的第二个元素时,它会抛出错误Exception in thread "main" java.lang.IllegalStateException at java.util.ArrayList$Itr.remove(Unknown Source)

这就是问题所在。

{  
  "date":"01/12/15",
  "time":"23:30"
}

1
@Gimby:不,链接的问题是关于JavaScript的,而这个问题是关于Java和Jackson的。 - Amadan
你能不能不使用ArrayNode?我不是Jackson用户,只是在API中看到它。 - Murat Karagöz
https://dev59.com/5ozda4cB1Zd3GeqPiR0C#30917454 - nafas
3个回答

4
for (JsonNode personNode : rootNode) {
    if (personNode instanceof ObjectNode) {
       if (personNode.has("showTimes")) {
          ObjectNode object = (ObjectNode) personNode;  
          object.remove("showTimes");
       }
    }
}

我认为使用personNode.isObject()而不是instanceof更好。 - Chanandler Bong

2

类似以下代码应该可以运行(我不是Jackson的用户,所以可能有所不同):

((ObjectNode) movieListElement).remove("showTimes");

编辑:

JsonNode movieListElement = ((ArrayNode) root.path("movieList").get(index);

1
乍一看,这似乎会删除整个 showTimes 字段。 - Gavin
是的。你说过"我想能够删除整个showTimes对象"。获取给定索引的正确movieList元素,就交给你了。 - Amadan
也许你错过了关于“给定索引”的部分。我可以轻松获取movieList元素。但是如何指定要删除的showTimes数组中的索引呢?我不想删除整个showTimes数组,而只是删除选定的索引。 - Gavin
movieListElement不是"movieList"节点,而是movieList数组的一个元素。你可以通过get(index)"movieList"ArrayNode中获取它。 - Amadan

1
像这样的应该可以工作。
public void removeShowTime(int pos){
    final JsonNode movieList = new ObjectMapper().readTree(json).get("movieList").get(0);
    final JsonNode showList = movieList.get("showtimesList");
    Iterator<JsonNode> itr = showList.iterator();
    int counter = 0
    while(itr.hasNext() && counter<=pos){
       if(counter==pos){
           itr.remove();
       }
       counter++;
    }
}

JSONArray 不是 Jackson。 - Amadan
@Amadan 哦,好的,我漏掉了关于Jackson的部分,正在修正答案。 - Sudheer
@Sudheer 如果我可以将showTimes字段作为List<ShowTime>对象获取,那么我该如何将其转换为JsonNode? - Gavin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接