1

I have an JSON array who looks like this:

[ {
  "name" : "1",
  "date" : "30/03 19:36:20"
}, {
  "name" : "12",
  "date" : "30/03 19:36:21"
}, {
  "name" : "123",
  "date" : "30/03 19:36:22"
}, {
  "name" : "1234",
  "date" : "30/03 19:36:23"
}, {
  "name" : "12345",
  "date" : "30/03 19:36:25"
} ]

How could I possibly delete one object by its name in java, like let's suppose I wanna delete the 1

 {
  "name" : "1",
  "date" : "30/03 19:36:20"
},

How could I possibly delete just those lines, because my code at the moment deletes all entries from the file

public static void deleteSavefile() throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode jsonNode = objectMapper.readTree(new File("savefiles.json"));
    for (JsonNode node : jsonNode) {
        ((ObjectNode)node).remove("name");
        ((ObjectNode)node).remove("date");
    }
    objectMapper.writeValue(new File("savefiles.json"), jsonNode);
}
6
  • What progress have you made till now? What approach are you following to parse and operate on this json? Commented Mar 30, 2019 at 19:41
  • I have a code but It removes all entries, not just one Commented Mar 30, 2019 at 19:42
  • @TerchilăMarian Which library are you using? Commented Mar 30, 2019 at 19:43
  • I'm using jackson Commented Mar 30, 2019 at 19:44
  • post the code here @TerchilăMarian Commented Mar 30, 2019 at 19:44

3 Answers 3

3

If jsonNode is an Array of Objects then jsonNode.elements() returns Iterator<JsonNode>, by using if condition check the node with name equals 1 then delete the entire node

 JsonNode jsonNode = objectMapper.readTree(new File("savefiles.json"));
Iterator<JsonNode> nodes = jsonNode.elements()
 while(nodes.hasNext()) {
     if(nodes.next().get("name").textValue().equals("1")){
           nodes.remove();
           }
       }
Sign up to request clarification or add additional context in comments.

3 Comments

Your code works except that it doesn't delete the brackets at the end of execution, [{},{"name":"12","date":"30/03 19:36:21"},{"name":"123","date":"30/03 19:36:22"},{"name":"1234","date":"30/03 19:36:23"},{"name":"12345","date":"30/03 19:36:25"}]
I've tried but still cannot get rid of the empty brackets
check the updated code @TerchilăMarian that should work
3

If you want to remove an element from the ArrayNode, just

final JsonNode json = objectMapper.readTree(new File("savefiles.json"));

if (json.isArray()) {
    for (final Iterator<JsonNode> i = json.elements(); i.hasNext(); ) {
        final JsonNode jsonNode = i.next();

        if ("1".equals(jsonNode.get("name").asText())) {
            i.remove();
        }
    }
}

This will not create a new instance. The original TreeNode (which is an ArrayNode) is maintained.
Note also the .asText() while comparing.

A Stream version is

final ArrayNode filtered =
        StreamSupport.stream(json.spliterator(), false)
                     .filter(e -> !"1".equals(e.get("name").asText()))
                     .collect(Collector.of(
                             objectMapper::createArrayNode,
                             (array, element) -> array.add(element),
                             (result, toMerge) -> result.addAll(toMerge)
                     ));

Comments

1

Read the json in the list, iterate on the list, find the element and remove it.

ObjectMapper objectMapper = new ObjectMapper();
// read in a list
List<Map<String, String>> jsonList = objectMapper.readValue(new File("savefiles.json"), new TypeReference<List<Map<String, String>>>(){});

// remove object with name "1"
jsonList = jsonList.stream().filter(e -> !"1".equals(e.get("name"))).collect(Collectors.toList());

You can simplify more by defining a bean class with two field name and date then instead of List<Map<String, String> you can use List<BeanClass>.

// read in a list
List<BeanClass> jsonList = objectMapper.readValue(new File("savefiles.json"), new TypeReference<List<BeanClass>>(){});

// remove object with name "1"
jsonList = jsonList.stream().filter(e -> !"1".equals(e.getName())).collect(Collectors.toList());

Wrote code directly here, there might be some typo.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.