尝试反序列化子类时出现“com.fasterxml.jackson.databind.exc.InvalidTypeIdException:无法解析类型 id”

Cia*_*C94 2 java json jackson jackson-databind

我正在尝试实现 JsonSubTypes,但我希望能够对无法识别的子类型进行一些优雅的处理。我使用的是 Jackson 2.9.7,并且无法进行更新,因为还有一些其他类依赖于它。

假设这是我的代码:

@Value.Style(allParameters = true, typeImmutable = "*", typeImmutableEnclosing = "*Impl",
    defaults = @Value.Immutable(builder = false))
@Value.Enclosing
@JsonSerialize
@JsonDeserialize
public class JsonAnimal {


  @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "subClass", include = JsonTypeInfo.As.EXISTING_PROPERTY,
      visible = true, defaultImpl = UnmappedAnimal.class) //fixme create logger warning if this defaults to a Void
  @JsonSubTypes({
      @JsonSubTypes.Type(value = Dog.class, name = Dog.ANIMAL_TYPE),
      @JsonSubTypes.Type(value = Cat.class, name = Cat.ANIMAL_TYPE),
      @JsonSubTypes.Type(value = Fish.class, name = Fish.ANIMAL_TYPE),
      @JsonSubTypes.Type(value = Hamster.class,
          name = Hamster.ANIMAL_TYPE)
  public static abstract class Animal {
    public abstract String subClass();
    //other code
  }
  @Value.Immutable
  @JsonDeserialize
  public abstract static class Dog extends Animal {
    public static final String ANIMAL_TYPE = "dog";
    //dog-specific code
  }

  @Value.Immutable
  @JsonDeserialize
  public abstract static class Cat extends Animal {
    public static final String ANIMAL_TYPE = "cat";
    //cat-specific code
  }

  @Value.Immutable
  @JsonDeserialize
  public abstract static class Fish extends Animal {
    public static final String ANIMAL_TYPE = "fish";
    //fish-specific code
  }

  @Value.Immutable
  @JsonDeserialize
  public abstract static class Hamster extends Animal {
    public static final String ANIMAL_TYPE = "hamster";
    //hamster-specific code
  }

  public class UnmappedAnimal extends Animal { /**/ }

Run Code Online (Sandbox Code Playgroud)

我实现了子类,因为 JSON 有效负载中的“动物”对象将具有不同的字段,具体取决于“子类”的值,例如子类“猫”的动物将具有其他子类没有的“livesLeft”字段。

现在假设我有这个 JSON 有效负载:

{
  "id": 123456,
  "animal": {
    "subType": "horse",
    /* everything else */
  }
}
Run Code Online (Sandbox Code Playgroud)

这会导致以下错误:

com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Could not resolve type id 'horse' as a subtype of [simple type, class my.project.path.apiobject.JsonAnimal$Animal]: known type ids = dog, cat, fish, hamster] (for POJO property 'animal')
Run Code Online (Sandbox Code Playgroud)

我该怎么做才能处理未映射的子类型?我应该只catch (InvalidTypeIdException)在解析 JSON 时使用吗?如果我能得到任何帮助,我将不胜感激。

编辑:我还应该问,我的JSON解析器的ObjectMapper启用了ACCEPT_CASE_INSENSITIVE_PROPERTIES和FAIL_ON_UNKNOWN_PROPERTIES,但是如果我有一个名为“SubClass”而不是“subClass”的属性,则不会被解析。

mdh*_*mdh 5

如果您像这样配置 objectMapper 实现

objectMapper.disable(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE);
Run Code Online (Sandbox Code Playgroud)

您可以实现优雅的操控。具有不可解析子类型的字段将被反序列化为 null。