Search code examples
javajsonjackson-databind

How do I remove a specific element from a json use Objectnode?


I want remove some value in from json. the json format is like this:

{
    "cod": "200",
    "message": 0.0135,
    "cnt": 40,
    "list": [
        {
            "dt": 1545598800,
            "main": {
                "temp": 267.03,
                "temp_min": 258.629,
                "temp_max": 267.03,
                "pressure": 741.31,
                "sea_level": 1034.85,
                "grnd_level": 741.31,
                "humidity": 72,
                "temp_kf": 8.4
            },
            "weather": [
                {
                    "id": 800,
                    "main": "Clear",
                    "description": "clear sky",
                    "icon": "01n"
                }
            ]
}

I want remove some data from json . How can i remove id , icon in weather? I try this :

(ObjectNode) rootNode.get("list").get(i).get("weather")).remove("id");

but its not correct and this error happen:

com.fasterxml.jackson.databind.node.ArrayNode cannot be cast to com.fasterxml.jackson.databind.node.ObjectNode

Solution

  • The problem is rootNode.get("list").get(i).get("weather") will return the weather array

    "weather": [
                {
                    "id": 800,
                    "main": "Clear",
                    "description": "clear sky",
                    "icon": "01n"
                }
            ]
    

    Then get the first ObjectNode and remove id

    (ObjectNode) rootNode.get("list").get(i).get("weather").get(0).remove("id");