1

I am trying to fetch values from a JsonNode in order to carry out some validations. However, I get null when i try to fetch the value using a predefined variable (String). When I fetch the same value using hardcoded key, it gives me the correct value.

I tried naming a new variable String as the key, but it does not seem to be working as expected.

boolean validateFormData(JsonNode formData) {
    System.out.println("1-" + formData.get("name"));
    
    String nameVar = "name";

    System.out.println("2-" + formData.get(nameVar));
    
    return false;
}

1-"Mohammed"

2-null

Is being printed I am not sure why. The reason I want to use a variable is because the keys are not fixed, they vary from Form to Form. I am new to stackoverflow so kindly ignore the formatting errors. I shall get better with time. Any help is appreciated, thanks in advance. Even if the question is repeated kindly point me to the right answer.

Community
  • 1
  • 1
Mohammed Idris
  • 768
  • 2
  • 9
  • 26
  • JsonNode class is from which library ? – TechFree Jun 17 '19 at 12:13
  • Can you try calling the variable-based get method first and telling us the results? If it returns a value but the normal one fails, then this could be a bug. Otherwise, you could always try [JsonNode.findValue(String fieldName)](https://fasterxml.github.io/jackson-databind/javadoc/2.2.0/com/fasterxml/jackson/databind/JsonNode.html#findValue(java.lang.String)) – Austin Schaefer Jun 17 '19 at 12:27
  • @TechFree, `JsonNode` is from `com.fasterxml.jackson.databind.JsonNode` library. I figured out a way to handle the get request. `formData.get(nameVar)` returns `JsonNode`. Its SysOut returns `"Mohammed"` with double quotes. I tried `formData.get(nameVar).textValue()` and it returns `Mohammed` without double quotes. – Mohammed Idris Jun 18 '19 at 07:20
  • @Mohammed Which version of jackson-databind.jar are you using ? This works for me, do you have some other code in between which probably is changing the nameVar ? Can you also print formData and see if that is fine ? Add the formData in your question. – TechFree Jun 18 '19 at 08:11
  • @TechFree I am using 2.9.8 version of jackson-databind. The problem was nameVar was not a string, it was being fetched from another `JsonNode`. Hence it was returning with double quotes. I used textValue and it works fine. Thanks for your time. – Mohammed Idris Jun 18 '19 at 10:57

0 Answers0