Saturday, July 12, 2014

Jackson Uses Getter Instead of Variable

Here's a tricky gotcha in Jackson. You have defined an object with private variables and created their respective getters and setters, and that all works well, then you add a convenience method named something like "getXXXX()" and then suddenly there is an extra property "XXXX" in your JSON document. This is because Jackson uses getters rather than variable to decide what properties to write to JSON.

This is demonstrated by the output of this class:
public class JacsksonTest {
private String str1 = "str1";
private String str2 = "str2";
private String str3 = "str3";
public String getStr1(){return str1;}
public String getStr2(){return str2;}
public String getStr4(){return "str4";}
public static void main(String[] args) throws Exception {
JacsksonTest testObj = new JacsksonTest();
ObjectWriter jsonWriter = (new ObjectMapper()).writerWithDefaultPrettyPrinter();
System.out.println(jsonWriter.writeValueAsString(testObj));
}
}

Output:
{
 "str1" : "str1",
 "str2" : "str2",
 "str4" : "str4"
}

Notice that "str3", which is defined as a member variable but doesn't have a getter, is missing from the document. Instead, "str4", which has a getter but not a member variable, that is added to the JSON output.

When adding convenience methods to these objects, it is therefore important to not start them with "get".

No comments:

Post a Comment