java中使用JacksonMap器注解的反序列化

ars1skjm  于 2023-10-20  发布在  Java
关注(0)|答案(1)|浏览(146)

我正在尝试使用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

有什么建议吗?还是我做错了什么

pzfprimi

pzfprimi1#

我可以通过以下更改使其工作:
1.在特定的类中,@NoArgConstructor@Getter就足够了。这个类看起来像这样:

@NoArgsConstructor
@Getter
public class StripeServiceConfiguration implements ServiceConfiguration {
    private Map<String, Object> jsonConfiguration;
}

1.添加了一个wrapper类:

@Data
public class ConfigWrapper {
    private ServiceConfiguration serviceConfiguration;
}

1.然后,使用 Package 器类进行反序列化,如下所示:

String json = "{\"serviceConfiguration\":{\"serviceType\":\"Stripe\",\"jsonConfiguration\":{\"key1\":\"value1\",\"key2\":\"value2\"}}}";
ConfigWrapper config = new ObjectMapper().readValue(json, ConfigWrapper.class);
  1. TypeOfService getServiceType();可能不需要此方法。所以,我把它清理干净了。界面现在看起来像这样:
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
              property = "serviceType")
@JsonSubTypes({
    @JsonSubTypes.Type(value = StripeServiceConfiguration.class, name = "Stripe"),
    @JsonSubTypes.Type(value = BrainServiceConfiguration.class, name = "Brain"),
})
public  interface ServiceConfiguration {
}

相关问题