3

I have something like this:

    { 
  "Person": {
    "Info": [{
      "name":"Becky",
      "age": 14
      }
    ]
  },
  "FruitsList": {
    "Fruits": [
      {
        "name": "avocado",
        "organic": true
      },
      {
        "name": "mango",
        "organic": true
      }
    ]
  },
  "VegetablesList": {
    "Vegetables": [
      {
        "name": "brocoli",
        "organic": true
      },
      {
        "name": "lettuce",
        "organic": true
      }
    ]
  }
}

I want to remove the array FruitsList and the VegetablesList or perhaps even Person array. Something like this.

{ 
  "Person": {
    "Info": [
      "name": "Becky",
      "age": 14
    ]
   },
  "Fruits": [
    {
      "name": "avocado",
      "organic": true
    },
    {
      "name": "mango",
      "organic": true
    }
  ],
  "Vegetables": [
    {
      "name": "brocoli",
      "organic": true
    },
    {
      "name": "lettuce",
      "organic": true
    }
  ]
}

I am not quite sure what methods to use with in JACKSON libraries to get the right result. I would much appreciate your help. Thanks in advance.

2
  • Your input JSON string seems invalid, Info is not a JSON array. Commented Nov 5, 2019 at 6:50
  • you can read the input into a Map<String, Object>, remove the keys and serialize the map back to json Commented Nov 5, 2019 at 6:58

1 Answer 1

1

A simple way is to remove FruitsList and VegetablesList nodes from root node first, and add Fruits and Vegetables back to it as follows:

ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(jsonStr);
JsonNode personNode = rootNode.get("Person");
JsonNode fruitsListNode = rootNode.get("FruitsList");
JsonNode vegetablesList = rootNode.get("VegetablesList");
((ObjectNode) rootNode).remove("FruitsList");
((ObjectNode) rootNode).remove("VegetablesList");
((ObjectNode) rootNode).put("Fruits", fruitsListNode.get("Fruits"));
((ObjectNode) rootNode).put("Vegetables", vegetablesList.get("Vegetables"));

System.out.println(rootNode.toString());

BTW, as I said in OP's comment, your JSON string is invalid. A valid one should be "Person": {"Info": {...}},....

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.