【发布时间】: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