我正在尝试使用Jackson
注解来解释以下json
。以下是我的当前代码:
@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;
}
}
支付服务
@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请求
{
"serviceConfiguration": {
"serviceType": "Stripe",
"jsonConfiguration": {
.....
....
}}}
Enum类
public enum TypeOfService {
STRIPE("Stripe"),
BRAIN("Brain")
}
获取错误
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
有什么建议吗?还是我做错了什么
1条答案
按热度按时间pzfprimi1#
我可以通过以下更改使其工作:
1.在特定的类中,
@NoArgConstructor
和@Getter
就足够了。这个类看起来像这样:1.添加了一个wrapper类:
1.然后,使用 Package 器类进行反序列化,如下所示:
TypeOfService getServiceType();
可能不需要此方法。所以,我把它清理干净了。界面现在看起来像这样: