alpha_boy
alpha_boy

Reputation: 99

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

Upvotes: 1

Views: 5745

Answers (2)

Vijay Kesanupalli
Vijay Kesanupalli

Reputation: 165

Try the below code it may work. First convert the JsonNode to ObjectNode

JsonNode yourJsonNode;
List<String> fieldsTobeRemoved = Arrays.asList("a","b");
if (!yourJsonNode.isMissingNode() && yourJsonNode instanceof ObjectNode && null != fieldsTobeRemoved) {
    ObjectNode yourObjectNode = (ObjectNode) yourJsonNode;
    fieldsToBeRemoved.forEach(field -> yourObjectNode.remove(field));
}

Upvotes: 0

Ryuzaki L
Ryuzaki L

Reputation: 40068

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

Upvotes: 1

Related Questions