【问题标题】:How to use dynamic deserialization on a property using JsonSubTypes?如何使用 JsonSubTypes 对属性使用动态反序列化?
【发布时间】:2020-06-22 12:53:01
【问题描述】:

我有一个类 Food 需要用作反序列化类。

public class Food {

    private VegetableConfiguration vegetableConfiguration;
    private Color color;

    // ...
    // Getters/Setters
}
public interface VegetableConfiguration {
    // ...
}
public class PotatoConfiguration implements VegetableConfiguration {
    // ...
}
public class CarrotConfiguration implements VegetableConfiguration {
    // ...
}
public class PepperConfiguration implements VegetableConfiguration {
    // ...
}
public enum Color {
    BROWN, ORANGE, RED
}

我需要根据从响应中得到的Color 选择一个实现VegetableConfiguration

我正在尝试使用 JsonTypeInfo 形式的杰克逊。根据 JavaDoc,它可以用于属性。

public class Food {


    @JsonTypeInfo(
            use = JsonTypeInfo.Id.NAME,
            property = "color")
    @JsonSubTypes({
            @JsonSubTypes.Type(value = PotatoConfiguration.class, name = "BROWN"),
            @JsonSubTypes.Type(value = CarrotConfiguration.class, name = "ORANGE"),
            @JsonSubTypes.Type(value = PepperConfiguration.class, name = "RED"),
    })
    private VegetableConfiguration vegetableConfiguration;
    private Color color;

    // ...
    // Getters/Setters
}

但它失败并出现以下错误

org.springframework.web.client.RestClientException: Error while extracting response for type [Food] and content type [application/json;charset=UTF-8]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Missing type id when trying to resolve subtype of [simple type, class VegetableConfiguration]: missing type id property 'color' (for POJO property 'vegetableConfiguration'); nested exception is com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Missing type id when trying to resolve subtype of [simple type, class VegetableConfiguration]: missing type id property 'color' (for POJO property 'vegetableConfiguration')

如何根据color 在反序列化时选择VegetableConfiguration 的实现?

最好不实现自定义反序列化器。

【问题讨论】:

  • 您使用哪个版本的Jackson?尝试将include = JsonTypeInfo.As.EXTERNAL_PROPERTY 配置添加到@JsonTypeInfo
  • @MichałZiober 成功了!随意写一个答案。我使用 2.9.8

标签: java json spring jackson deserialization


【解决方案1】:

您需要使用JsonTypeInfo.As.EXTERNAL_PROPERTY。来自文档:

包含机制类似于PROPERTY除了属性是 在层次结构中包含更高一级,即作为兄弟属性 与要键入的 JSON 对象级别相同。请注意,此选择只能是 用于属性,而不是类型(类)。试图将其用于 类将导致包含基本属性的策略。

另见:

【讨论】:

    猜你喜欢
    • 2015-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-05
    相关资源
    最近更新 更多