Friday, January 7, 2011

JSON deserialization with Jackson

Recently I was trying to deserialize a Java object with Jackson.  I had a specific JSON property name needed so my Java Bean looked like this:



public class RequestInfo
{
    @JsonProperty("first")
    private String firstName;


    @JsonProperty("last")
    private String lastName;


   ...Getters and setters normal.
}

I had a list of RequestInfo in an ArrayList.  When trying to deserialize that ArrayList with the Jackson JSON processor, I had duplicate entries...


[{"first":"Matt","last":"Dimich","firstName":"Matt","lastName":"Dimich"}]


To fix this, I had to use the @JsonIgnoreProperties annotation.

I used it to include a list of properties that Jackson should NOT include when deserializing.  The solution was adding this line to the class file.
@JsonIgnoreProperties({"firstName", "lastName"})

The final result of my Class then looked like this:


@JsonIgnoreProperties({"firstName", "lastName"})
public class RequestInfo
{
    @JsonProperty("first")
    private String firstName;

    @JsonProperty("last")
    private String lastName;

   ...Getters and setters normal.
}

OUTPUT:

[{"first":"Matt","last":"Dimich"}]


No comments:

Post a Comment