gpt4 book ai didi

java - 尝试反序列化子类时出现"com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Could not resolve type id"

转载 作者:行者123 更新时间:2023-12-03 08:13:57 29 4
gpt4 key购买 nike

我正在尝试实现 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 { /**/ }

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

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

{
"id": 123456,
"animal": {
"subType": "horse",
/* everything else */
}
}

这会导致以下错误:

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')

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

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

最佳答案

如果您像这样配置 objectMapper 实现

objectMapper.disable(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE);

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

关于java - 尝试反序列化子类时出现"com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Could not resolve type id",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70035423/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com