Reputation: 2824
How do I remove the object of JSON? I am using Jackson API 2.6.3
Example of my JSON String
{
"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"
}
]
}
]
}
I would like to be able to remove the whole showTimes object given its index.
Something like showtimesList.get(index).remove()
And if it is the last object in the arrayList, the value should be set to null
.
As suggested by one of the answer, I am converting the JAVA Object ShowTime
to JSONNode by so
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++;
}
But it's throwing the error Exception in thread "main" java.lang.IllegalStateException
at java.util.ArrayList$Itr.remove(Unknown Source)
when I tries to remove the 2nd element of showTimes
on the above given JSON String
Which is
{
"date":"01/12/15",
"time":"23:30"
}
Upvotes: 3
Views: 17365
Reputation: 131
Something like this should work
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++;
}
}
Upvotes: 1
Reputation: 198324
Something like this should work (I'm not a Jackson user, so YMMV):
((ObjectNode) movieListElement).remove("showTimes");
EDIT:
JsonNode movieListElement = ((ArrayNode) root.path("movieList").get(index);
Upvotes: 2
Reputation: 2351
for (JsonNode personNode : rootNode) {
if (personNode instanceof ObjectNode) {
if (personNode.has("showTimes")) {
ObjectNode object = (ObjectNode) personNode;
object.remove("showTimes");
}
}
}
Upvotes: 4