I am using Jackson and I'm having problems, when I try to deserialize an Object I get the following error:
com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of net.MyAbstractClass, problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information
I am having problems in the attribute:
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT, property = "@id") @JsonSubTypes({ @JsonSubTypes.Type(value = MyAbstractClass.class, name = "MyAbstractClass") }) @ManyToOne private MyAbstractClass object;
Could anyone help me?
Jackson uses default (no argument) constructor to create object and then sets value using setters. so you only need @NoArgsConstructor and @Setter.
The Problem. First, let's take a look at JsonMappingException: Can Not Construct Instance Of. This exception is thrown if Jackson can't create an instance of the class, which happens if the class is abstract or it is just an interface.
To Solve No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator Error You Just need to Add an empty constructor Just like this: @JsonProperty(“field_name”) Second solution is This Solution is very similar to Solution 1 You just need to add a default ...
public class JsonProcessingException extends IOException. Intermediate base class for all problems encountered when processing (parsing, generating) JSON content that are not pure I/O problems. Regular IOException s will be passed through as is. Sub-class of IOException for convenience. See Also: Serialized Form.
You cannot instantiate an abstract class, Jackson neither. You should give Jackson information on how to instantiate MyAbstractClass with a concrete type.
See this answer on stackoverflow: Jackson JSON library: how to instantiate a class that contains abstract fields
And maybe also see Jackson Polymorphic Deserialization
You need to use a concrete class and not an Abstract class while deserializing. if the Abstract class has several implementations then, in that case, you can use it as below-
@JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes({ @Type(value = Bike.class, name = "bike"), @Type(value = Auto.class, name = "auto"), @Type(value = Car.class, name = "car") }) public abstract class Vehicle { // fields, constructors, getters, setters }
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