1

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": [
        "ISP3100008972@some.com"
    ]
}

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.

  • So have you looked in a debugger to see whether it's `objNode` that's null or `objNode.get(0)` that's null? – Jon Skeet Mar 19 '20 at 05:18
  • I've added an answer, but next time you're in a similar situation, the first thing to work out is what's null. If you'd found that `objNode` is non-null, but `objNode.get(int)` was null, and you'd looked at the concrete type of `objNode` in the debugger and looked at the documentation for `JsonNode.get(int)`, I suspect you could have found the problem without asking a question. (That's a good habit to get into: every time you ask a question, when it's been solved, ask yourself what skills you could have applied to solve it yourself.) – Jon Skeet Mar 19 '20 at 05:22

1 Answers1

1

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();
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thanks @Jon Skeet. I am happy with your explanation, It's working now. – Javier Irrazábal Mar 19 '20 at 06:13
  • How do we handle Null Pointer Exception though? I am checking whether the node exists or not, and accordingly I throw an exception. I don't want to explicitly through NPE as it is not considered good practise. Any thoughts? Below is an eg if(jsonNode["viewModelId"] != null) { int viewModelId = (int)jsonNode?["viewModelId"]!; } else { throw new Exception("Error parsing View Model ID"); } – Avneet Singh Aug 10 '23 at 18:07
  • @AvneetSingh: I answered the question in a way that would avoid the OP receiving an NPE to start with. It sounds like your situation is different. I wouldn't fetch `jsonNode["viewModelId"]` twice though: fetch it once and store in a local variable, and then check for nullity and either throw or cast depending on the result. (But not just `Exception`...) – Jon Skeet Aug 10 '23 at 18:38