I have polymorphic types and deserializing from JSON to POJO works. I followed the documentation here, in fact. When serializing POJOs into JSON I'm getting an unwanted attribute, specifically the logical type name.
import static org.codehaus.jackson.annotate.JsonTypeInfo.*;
@JsonTypeInfo(use=Id.NAME, include=As.PROPERTY, property="type")
@JsonSubTypes({
@JsonSubTypes.Type(value=Dog.class, name="dog"),
@JsonSubTypes.Type(value=Cat.class, name="cat")
})
public class Animal { ... }
public class Dog extends Animal { ... }
public class Cat extends Animal { ... }
When Jackson serializes into JSON it provides the type information which I don't want to expose.
{"type":"dog", ... }
{"type":"cat", ... }
Can I prevent this somehow? I only want to ignore type when deserializing.
If there are fields in Java objects that do not wish to be serialized, we can use the @JsonIgnore annotation in the Jackson library. The @JsonIgnore can be used at the field level, for ignoring fields during the serialization and deserialization.
Advertisements. let's serialize a java object to a json file and then read that json file to get the object back. In this example, we've created Student class.
Note that Jackson does not use java. io. Serializable for anything: there is no real value for adding that. It gets ignored.
Jackson can't serialize private fields - without accessor methods - with its default settings. PrivatePerson has two private fields with no public accessors.
A simple solution would be to just move the @JsonTypeInfo and @JsonSubTypes configs to a MixIn, and then only register the MixIn for deserialization.
mapper.getDeserializationConfig().addMixInAnnotations(MyClass.class, MyMixIn.class)
This took me a long time to solve so I thought I'd share.
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY,
visible = false, property = "type")
visible=false ensures that if the property type exists on the class, it will not be populated with the value of type during deserialization.
include = JsonTypeInfo.As.EXISTING_PROPERTY dictates that if the property type exists, use that value during serialization otherwise do nothing.
So putting it all together:
import static org.codehaus.jackson.annotate.JsonTypeInfo.*;
@JsonTypeInfo(use = Id.NAME, include = As.EXISTING_PROPERTY, visible = false, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value=Dog.class, name="dog"),
@JsonSubTypes.Type(value=Cat.class, name="cat")
})
public class Animal { ... }
public class Dog extends Animal { ... }
public class Cat extends Animal { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With