There is difference in between these 2 methods

  1. JsonNode.get() method returns null
  2. Use JsonNode.path(String).asText() which checks if node is present or not, if not then it returns empty string.
Answer from MukulChakane on Stack Overflow
🌐
Fasterxml
fasterxml.github.io › jackson-databind › javadoc › 2.6 › com › fasterxml › jackson › databind › JsonNode.html
JsonNode (jackson-databind 2.6.0 API) - FasterXML
public abstract JsonNode get(int index) Method for accessing value of the specified element of an array node. For other nodes, null is always returned. For array nodes, index specifies exact location within array and allows for efficient iteration over child elements (underlying storage is ...
Discussions

java - JsonNode.get("") returns null value. I want to take "name" and "forks" from json on code - Stack Overflow
RestTemplate restTemplate = new ... mapper = new ObjectMapper(); //mapper JsonNode jsonTree = mapper.readTree(response); //JsonNode System.out.println(jsonTree.get("name")); //null... More on stackoverflow.com
🌐 stackoverflow.com
June 27, 2022
Missing JsonNode field deserialized to null instead of NullNode
Describe the bug There's a behavior change between 2.12.6 and 2.13.0. Until then a missing JsonNode field was deserialized as a NullNode and it now is deserialized to Java null. Version informa... More on github.com
🌐 github.com
3
January 31, 2022
java - JsonNode.get().asText() returning null - Stack Overflow
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.JsonN... More on stackoverflow.com
🌐 stackoverflow.com
java - Check if JSON node is null - Stack Overflow
I'm returning some JSON from an api, and one of the child nodes of the root object is item. I want to check whether this value at this node is null. Here's what I'm trying, which is currently thro... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Stack Overflow
stackoverflow.com › questions › 72775684 › jsonnode-get-returns-null-value-i-want-to-take-name-and-forks-from-json
java - JsonNode.get("") returns null value. I want to take "name" and "forks" from json on code - Stack Overflow
June 27, 2022 - RestTemplate restTemplate = new RestTemplate(); String resourceUrl = "https://api.github.com/orgs/engineyard/repos"; //json address String response = restTemplate.getForObject(resourceUrl,String.class); ObjectMapper mapper = new ObjectMapper(); //mapper JsonNode jsonTree = mapper.readTree(response); //JsonNode System.out.println(jsonTree.get("name")); //null
🌐
Fasterxml
fasterxml.github.io › jackson-databind › javadoc › 2.4 › com › fasterxml › jackson › databind › node › NullNode.html
NullNode (jackson-databind 2.4.0 API)
Will return the first JsonToken that equivalent stream event would produce (for most nodes there is just one token but for structured/container types multiple) ... Method similar to JsonNode.asText(), except that it will return defaultValue in cases where null value would be returned; either ...
🌐
Tabnine
tabnine.com › home page › code › java › com.fasterxml.jackson.databind.jsonnode
com.fasterxml.jackson.databind.JsonNode.isNull java code examples | Tabnine
public static String getValueAsString(String name, JsonNode objectNode) { String propertyValue = null; JsonNode propertyNode = objectNode.get(name); if (propertyNode != null && !propertyNode.isNull()) { propertyValue = propertyNode.asText(); } return propertyValue; }
🌐
GitHub
github.com › FasterXML › jackson-databind › issues › 3389
Missing JsonNode field deserialized to null instead of NullNode · Issue #3389 · FasterXML/jackson-databind
January 31, 2022 - Describe the bug There's a behavior change between 2.12.6 and 2.13.0. Until then a missing JsonNode field was deserialized as a NullNode and it now is deserialized to Java null. Version information Behavior change occurs since 2.13.0 To ...
Author   the8tre
🌐
Red Hat
access.redhat.com › webassets › avalon › d › red-hat-jboss-enterprise-application-platform › 7.1.beta › javadocs › com › fasterxml › jackson › databind › JsonNode.html
JsonNode (Red Hat JBoss Enterprise Application Platform 7.1.0.Beta1 public API)
NOTE: if the property value has been explicitly set as null (which is different from removal!), a NullNode will be returned, not null. ... Node that represent value of the specified field, if this node is an object and has value for the specified field. Null otherwise.
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 79626147 › jsonnode-get-astext-returning-null
java - JsonNode.get().asText() returning null - Stack Overflow
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.JsonN...
Top answer
1 of 1
1

The issues lies in the meaning of null in this context. In the problematic case, clearly op has been instantiated and is therefore not null. This can be shown by adding another output line in the constructor performing the validation:

System.out.println("    class:" + (null == op ? "Real Null" : op.getClass().toString()));

This, when the program is run again, produces the folloiwng output:

Initial value: {"type":"CREATE","op":null}
Document value: {"@type":"CrudOperation","type":"CREATE"}
 isUpdate: false
isNotNull: false
  isValid: false
    class:class com.fasterxml.jackson.databind.node.NullNode
com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of com.cyberfront.test.json.nll.demonstration.CrudOperation, problem: Operation Failed Validation: {"type":"CREATE","op":null}
 at [Source: N/A; line: -1, column: -1]
Reconstructed: null

That is, op is instantiated as a NullNode object type, which when the toString() method is performed upon it, returns null as a string not as the type.

A solution to resolving this is use of the JsonNode.isNull() method to detect when this case arises.

@JsonCreator
public CrudOperation(@JsonProperty("type") Type type, @JsonProperty("op") JsonNode op) {
    this.type = type;
    this.op = null == op || op.isNull() ? null : op;

    boolean isUpdate = Type.UPDATE.equals(this.getType());
    boolean isNotNull = null == this.getOp();
    boolean isValid = isUpdate ^ isNotNull;

    if (!isValid) {
        System.out.println(" isUpdate: " + String.valueOf(isUpdate));
        System.out.println("isNotNull: " + String.valueOf(isNotNull));
        System.out.println("  isValid: " + String.valueOf(isValid));
        System.out.println("    class:" + (null == op ? "Real Null" : op.getClass().toString()));

        throw new IllegalArgumentException("Operation Failed Validation: " + this.toString());
    }
}

This additional check for isNull() will filter out the case where a JsonNode is an instantiated null node, and will provide

Initial value: {"type":"CREATE","op":null}
Document value: {"@type":"CrudOperation","type":"CREATE"}
Reconstructed: {"type":"CREATE","op":null}

This achieves the desired result.

Top answer
1 of 2
1

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.

2 of 2
0

While the solution in the other answer works, I think you can make it easier and more natural for yourself by doing more modelling in Java, which will allow you to leave more of the parsing work to Jackson. In addition to your Solution class (which should be spelled with an uppercase letter as all Java class names) also write a little class to reflect your entire JSON. I recommend a record type:

record Problems (@JsonProperty("Solution") List<Solution> solution) {
    public List<Solution> solutions() {
        return Collections.unmodifiableList(solution);
    }
}

Alternatively a classic class will work too:

public class Problems {
    @JsonProperty("Solution")
    private List<Solution> solution;

    public List<Solution> getSolution() {
        return Collections.unmodifiableList(solution);
    }
}

I added the @JsonProperty annotation to inform Jackson that Solution is spelled with uppercase S in JSON even though the variable in Java must be spelled with a small s.

Now your method can be written like the following. I have inlined the JSON for a reproducible example.

    public static Solution findSolution(String name){
        String 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++"
                
                    }
                  ]
                }""";
        ObjectMapper mapper = new ObjectMapper();
        try {
            Problems problems = mapper.readValue(json, Problems.class);
            return problems.solution() // with the *class* Problems use .getSolution()
                    .stream()
                    .filter(sol -> sol.getName().equals(name))
                    .findAny()
                    .orElseThrow();
        } catch (JsonProcessingException e){
            e.printStackTrace();
        }
        System.out.println("problem doesnt exist");
        return null;
    }

In your code you can just use

            Problems problems = mapper.readValue(file, Problems.class);

If you are not comfortable with the stream operation, you may also use a loop for finding the solution with the requested name.

Let’s try it out:

    Solution sol = findSolution("Watermelon");
    System.out.println(sol);

Output from the latter line is:

Solution{name='Watermelon', difficulty='easy', status='working', lastModified='05-02-2024', testCase='false', source='codeforces.com', language='C++'}

🌐
GitHub
github.com › FasterXML › jackson-databind › issues › 3214
For an absent property Jackson injects `NullNode` instead of `null` to a JsonNode-typed constructor argument of a `@ConstructorProperties`-annotated constructor · Issue #3214 · FasterXML/jackson-databind
July 15, 2021 - Describe the bug When using @ConstructorProperties-annotated constructor to deserialize type, for an attribute of type JsonNode which is absent from the deserialized JSON, a NullJsonNode is passed to the constructor instead of null reference.
Author   robvarga
🌐
Fasterxml
fasterxml.github.io › jackson-databind › javadoc › 2.7 › com › fasterxml › jackson › databind › JsonNode.html
JsonNode (jackson-databind 2.7.0 API)
public abstract JsonNode get(int index) Method for accessing value of the specified element of an array node. For other nodes, null is always returned. For array nodes, index specifies exact location within array and allows for efficient iteration over child elements (underlying storage is ...
🌐
Stack Overflow
stackoverflow.com › questions › 79626147 › jsonnode-get-astex-returning-null
java - JsonNode.get().asTex() returning null - Stack Overflow
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.
🌐
Fasterxml
fasterxml.github.io › jackson-databind › javadoc › 2.4 › com › fasterxml › jackson › databind › JsonNode.html
JsonNode (jackson-databind 2.4.0 API)
public abstract JsonNode get(int index) Method for accessing value of the specified element of an array node. For other nodes, null is always returned. For array nodes, index specifies exact location within array and allows for efficient iteration over child elements (underlying storage is ...
Top answer
1 of 2
2
https://fasterxml.github.io/jackson-databind/javadoc/2.8/com/fasterxml/jackson/databind/JsonNode.html#get(java.lang.String) public JsonNode get(String fieldName) Method for accessing value of the specified field of an object node. If this node is not an object (or it does not have a value for specified field name), or if there is no field with such name, null is returned. NOTE: if the property value has been explicitly set as null (which is different from removal!), a NullNode will be returned, not null. https://fasterxml.github.io/jackson-databind/javadoc/2.8/com/fasterxml/jackson/databind/JsonNode.html#asText() public abstract String asText() Method that will return a valid String representation of the container value, if the node is a value node (method isValueNode() returns true), otherwise empty String. When you call isEmpty() on the result of asText() you are calling the String.isEmpty() https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#isEmpty() From what I can tell the JsonSerializable.Base class doesn't have an isEmpty() method only an isEmpty(SerializerProvider serializers) https://fasterxml.github.io/jackson-databind/javadoc/2.8/com/fasterxml/jackson/databind/JsonSerializable.Base.html
2 of 2
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
🌐
Adobe Developer
developer.adobe.com › experience-manager › reference-materials › cloud-service › javadoc › com › fasterxml › jackson › databind › node › NullNode.html
NullNode (The Adobe Experience Manager SDK 2022.11.9850.20221116T162329Z-220900)
public static NullNode getInstance() public JsonNodeType getNodeType() Description copied from class: JsonNode · Return the type of this node · Specified by: getNodeType in class JsonNode · Returns: the node type as a JsonNodeType enum value · public JsonToken asToken() Description copied from class: BaseJsonNode ·
🌐
Red Hat
access.redhat.com › webassets › avalon › d › red_hat_jboss_enterprise_application_platform › 8.0 › javadocs › com › fasterxml › jackson › databind › JsonNode.html
JsonNode (Red Hat JBoss Enterprise Application Platform 8.0.0.GA public API)
NOTE: if the property value has been explicitly set as null (which is different from removal!), a NullNode will be returned, not null. ... Node that represent value of the specified field, if this node is an object and has value for the specified field. Null otherwise. public abstract JsonNode ...
Top answer
1 of 2
1

According to the JSON structure, the first items must be fetched, and since it is a list, the first items must be fetched based on index. 

 String title = volumeNode.get("items").get(0).get("volumeInfo").get("title").textValue();
2 of 2
1

Well, "title" is not a property at the top level of your JSON so when it searches for such property it finds nothing and returns null. Also it seems to me that your code may be a bit too complex. You didn't provide your GoogleVolume class. However by its structure it should be the same as the structure of your JSON. What I would suggest that you use ObjectMapper method: public T readValue(String content, Class valueType) throws JsonProcessingException, JsonMappingException where the second parameter would be your GoogleVolume.class. Or You can try use Map.class to parse your JSON String to instance of Map<String, Object>. Also if I may suggest to simplify your code even further I wrote my own Open Source library called MgntUtils that provides (among other utils) a very simple Http client and JsonUtil for simple cases of serializing/parsing JSON. your code with use of my library may look something like this:

HttpClient httpClient = new HttpClient();
String jsonResponse = httpClient.sendHttpRequest(urlStr, HttpClient.HttpMethod.GET);
GoogleVolume volume = JsonUtils.readObjectFromJsonString(jsonResponse, GoogleVolume.class); 

For simplicity I omitted exception handling. Here is the Javadoc for MgntUtils library. The library can be obtained as Maven artifact from Maven Central or from Github (including Javadoc and source code)