I am trying to deserialize the following json
using Jackson
annotations. Here is my current code:
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "serviceType")
@JsonSubTypes({
@JsonSubTypes.Type(value = StripeServiceConfiguration.class, name = "Stripe"),
@JsonSubTypes.Type(value = BrainServiceConfiguration.class, name = "Brain"),
})
public interface ServiceConfiguration {
TypeOfService getServiceType();
}
StripeService
@Data
public class StripeServiceConfiguration implements ServiceConfiguration {
private static final TypeOfService serviceType = TypeOfService.STRIPE;
private Map<String, Object> jsonConfiguration;
@Override
public TypeOfService getServiceType() {
return serviceType;
}
}
OtherPaymentService
@Data
public class BrainServiceConfiguration implements ServiceConfiguration {
private static final TypeOfService serviceType = TypeOfService.BRAIN;
private Map<String, Object> jsonConfiguration;
@Override
public TypeOfService getServiceType() {
return serviceType;
}
}
Json request
{
"serviceConfiguration": {
"serviceType": "Stripe",
"jsonConfiguration": {
.....
....
}}}
Enum class
public enum TypeOfService {
STRIPE("Stripe"),
BRAIN("Brain")
}
Error I am getting
Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot
construct instance of `com.example.models.payment.ServiceConfiguration` (no Creators,
like default constructor, exist): abstract types either need to be mapped to concrete
types, have custom deserializer, or contain additional type information
Any hint to fix it? or what am I doing wrong here?
2
Answers
Please add default constructors to
StripeServiceConfiguration
andBrainServiceConfiguration
classes.Jackson
relies on default constructors to serialize the beans.It looks like you also using Lombok library. Add to your classes
StripeServiceConfiguration
andBrainServiceConfiguration
annotation@NoArgumentsConstructor
. Also, if you struggle with expected Json structure, create some test where you create instances ofStripeServiceConfiguration
andBrainServiceConfiguration
classes and serialize them with Jackson’sObjectMapper
. This way you will get valid Json for your classes. Actually, for those purposes, there is a sd party Utility called JsonUtils which is a thin wrapper over ObjectMapper. The advantage of using it is that you don’t need to instanciate ObjectMapper yourself and can just serialize any class instance with one line:It might be helpful. Here is Javadoc for JsonUtils. This utility comes as part of MgntUtils Open Source library written and maintained by me. You can get the library as Maven artifact or from GitHub (including source code and Javadoc)