JsonNode - null pointer exception

Javier Irrazábal :

I need to get the value in this arrayNode (Just in case, I know it's going to be only one value in the array - Please, don't ask me why, It is the way that I'm receiving it):

"data": {
    "services": [
        "[email protected]"
    ]
}

I'm running this portion of code:

ArrayNode arrNode = (ArrayNode) new ObjectMapper().readTree(resBody).path("data").get("services");
if (arrNode.isArray()) {
    for (final JsonNode objNode : arrNode) {
        serviceId = objNode.get(0).textValue();
        log.info("serviceId: " + serviceId + " is available");
    }
}

I am getting a java.lang.NullPointerException: null in this line: serviceId = objNode.get(0).textValue();

Please, can anyone take a look at this? It would be highly appreciated.

Jon Skeet :

You're calling objNode.get(0), which would retrieve the first value of an array if objNode were an array node - but it's not, it's the node within the array. JsonNode.get(int) is documented to return null if the node isn't an array.

You just need:

serviceId = objNode.textValue();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=317099&siteId=1