Skip to content
Advertisement

Jackson ObjectMapper returns null when Object variable is set to Private

I am given this escaped JSON

JavaScript

and I need to convert it to Java object using Jackson.

JavaScript

I created the class:

JavaScript

Then I created the method to convert it

JavaScript

Whichever variables in Data class that are set to public, then I will get the corresponding value when I call getters. Whichever variables in Data class that are set to private, then I will get null when I call getters.

Getters and Setters are always public.

I am wondering, why ObjectMapper can’t map the object if it is set to private? I could set it to public, but that is not best practice.

Advertisement

Answer

The issue is that Jackson will always assume setSuccess() & getSuccess() will be used for a success field, not Success. JSON field names starting with uppercase letters need to be supported by @JsonProperty. Java has a convention where class members always start with lowercase letters, you can realize that by using this annotation.

When you make fields private, you force Jackson to utilize setters, and the above conflict makes it impossible to properly deserialize the Data object.

Solution is to do;

JavaScript

Then you will see the values deserialized properly into a Java object;

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement