0

My JSON looks like below and I need to remove the first object from secondArray.

{
   "firstArray":[
      {
         "data1":1,
         "data2":"DATA"
      },
      {
         "data1":2,
         "data2":"DATA2"
      }
   ],
   "secondArray":[
      {
         "number":1,
         "data":"DATA3",

      },
      {
         "number":2,
         "data":"DATA4"
      }
   ]
}

This is what I have so far:

public boolean remove(SecondArray object) {
 try {
  ObjectNode root = (ObjectNode) mapper.readTree(jsonFile);
  ArrayNode array = (ArrayNode) root.get("secondArray");
  if (array.path("number").asInt() == object.getId()) {
   movieArray.remove(object.getId());
  }
  System.out.println(array.toString());

 } catch (IOException e) {
  e.printStackTrace();
 }
}

My problem is that object.getId() gets the id as number but in JSON it comes inside " ". How do I make this work, so I could remove the object entered from secondArray?

1 Answer 1

1

Do not remove array item by object.id. Remove it by index. You need to iterate over array, find JSON Object where number = object.id and remove it. Example:

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);
    }
}

Above code prints:

[{"number":2,"data":"DATA4"}]
{"firstArray":[{"data1":1,"data2":"DATA"},{"data1":2,"data2":"DATA2"}],"secondArray":[{"number":2,"data":"DATA4"}]}
Sign up to request clarification or add additional context in comments.

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.