Can Jackson polymorphic deserialization be used to serialize to a subtype if a specific field is present?

As of Jackson 2.12.2, the following accomplishes the goal using the “deduction-based polymorphism” feature. If properties distinct to the Bird subtype (i.e. wingspan) are present, the deserialized type will be Bird; else it will be Animal: @JsonTypeInfo(use=Id.DEDUCTION, defaultImpl = Animal.class) @JsonSubTypes({@Type(Bird.class)}) public class Animal { public String name; public int age; } Deduction-based polymorphism The …

Read more

Jackson – Deserialize Generic class variable

You will need to build JavaType explicitly, if generic type is only dynamically available: // do NOT create new ObjectMapper per each request! final ObjectMapper mapper = new ObjectMapper(); public Json<T> void deSerialize(Class<T> clazz, InputStream json) { return mapper.readValue(json, mapper.getTypeFactory().constructParametricType(Json.class, clazz)); }

How to make Jackson ignore a get() method when serializing an object

If you mark the getter method with the @JsonIgnore annotation it should not be serialized. Here is an example: public class JacksonIgnore { public static class Release { public final String version; public Release(String version) { this.version = version; } } public static class Project { public final String name; public Project(String name) { this.name …

Read more

Jackson: Multiple back-reference properties with name ‘defaultReference’

If you use @JsonBackReference on more than one getter/setter method in your project, you should distinguish them with a specific reference name. Maybe only one ‘defaultReference’ is allowed in the latest version? e.g In MovementView.java @JsonBackReference(value=”user-movement”) public User getUser() { return user; } In User.java @JsonManagedReference(value=”user-movement”) public MovementView getMovementView() { return movementView; }

Jackson read json in generic List

Something which is much shorter: mapper.readValue(jsonString, new TypeReference<List<EntryType>>() {}); Where EntryType is a reference to type you would like to hold within collection. It might be any Java class. For example to read JSON representation such as [“a”, “b”, “c”] second argument to mapper should be new TypeReference<List<String>>() {}

jackson Unrecognized field

Jackson provides a few different mechanisms to configure handling of “extra” JSON elements. Following is an example of configuring the ObjectMapper to not FAIL_ON_UNKNOWN_PROPERTIES. import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility; import org.codehaus.jackson.annotate.JsonMethod; import org.codehaus.jackson.map.DeserializationConfig; import org.codehaus.jackson.map.ObjectMapper; public class JacksonFoo { public static void main(String[] args) throws Exception { // { “aaa”:”111″, “bbb”:”222″, “ccc”:”333″ } String jsonInput = “{ \”aaa\”:\”111\”, …

Read more