JsonNode.get().asText() returning null

JsonNode.get().asText() returning null
java
Ethan Jackson

I'm trying to create a pojo from a json file. But, for some reason "node.get("name").asText()" returns null.

The error happens at line 8 and here's what the debugger throws.

java.lang.NullPointerException: Cannot invoke "com.fasterxml.jackson.databind.JsonNode.asText()" because the return value of "com.fasterxml.jackson.databind.JsonNode.get(String)" is null.

I've already tried "node.get("solution").get("name").asText()" and switching "asText()" to "toString()", the result was the same.

Code fragment:

public static solution findSolution(String name){ File file = new File("/home/clementino/IdeaProjects/helloworldJava/problems.json"); ObjectMapper mapper = new ObjectMapper(); solution solution = new solution(); try { JsonNode tree = mapper.readTree(file); for(JsonNode node : tree){ if(node.get("name").asText().equalsIgnoreCase(name)){ //problema solution = mapper.treeToValue(node, solution.class); System.out.println(solution.getName()); }else{ System.out.println("problem doesnt exist"); } } }catch(Exception e){ System.out.println("error"); } return solution; }

problems.json:

{ "solution": [ { "name":"twoSum", "difficulty": "easy", "status": "time exceeded", "lastModified": "12-05-2025", "testCase": false, "source": "leetcode.com", "language": "java" }, { "name": "Watermelon", "difficulty": "easy", "status": "working", "lastModified": "05-02-2024", "testCase": false, "source": "codeforces.com", "language": "C++" } ] }

Answer

could you try this code?

JsonNode tree = mapper.readTree(file); JsonNode solutionsArray = tree.get("solution"); if (solutionsArray != null && solutionsArray.isArray()) { for (JsonNode node : solutionsArray) { if (node.get("name") != null && node.get("name").asText().equalsIgnoreCase(name)) { solution = mapper.treeToValue(node, solution.class); System.out.println(solution.getName()); } else { System.out.println("problem doesn't exist"); } } }

I think the issue is that you're trying to iterate over the root JsonNode, but your JSON structure wraps the actual array inside a solution field. Therefore, tree is not an array, and calling .get("name") on it will return null, causing the NullPointerException.

Related Articles