Jackson多态对象序列化/反序列化-未填充子类字段



我有多态类层次结构,需要向REST-Api发送/从REST-Api检索。

@JsonIgnoreProperties(ignoreUnknown = true) 
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = 
JsonTypeInfo.As.PROPERTY, property = "@class")
public class Property implements IProperty, Serializable {
private static final long serialVersionUID = 1L;
private String name;

例如,它的一个孩子:

public class PropertyEnum extends Property {
private static final long serialVersionUID = 1L;
private String value;
private Collection<String> values = new LinkedList<String>();

当将Property[]数组发送到rest资源或将其取回时,PropertyEnum中的值字段为空且未填充!另一方面填充值字段。名称被填充是肯定的,因为它在父类上。

我也试过了:

//@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", include =JsonTypeInfo.As.EXTERNAL_PROPERTY)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, 
property = "name")
@JsonSubTypes(value = { 
@JsonSubTypes.Type(value = PropertyEnum.class, name = "enum")
})
@JsonTypeName("enum")
public class PropertyEnum extends Property {

(尽管如此,添加新类型时需要始终维护代码!)

再试一次:

@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, 
property="objectType")
@JsonSubTypes({
@JsonSubTypes.Type(value=PropertyEnum.class)
})
public class Property implements IProperty, Serializable {
private static final long serialVersionUID = 1L;
private String name;
protected Property(){}

@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, 
property="objectType")
public class PropertyEnum extends Property {
private static final long serialVersionUID = 1L;
private String value;
private Collection<String> values = new LinkedList<String>();
protected PropertyEnum(){}

但我有一个奇怪的行为。。。一个子字段填充(值),另一个子字段(值)不填充?我有二传手/传接球手!

知道吗?

谨致问候。

我仍然不明白为什么一个字段没有填充,而其他字段则填充了,但我通过在有问题的字段中添加注释@JsonProperty来解决了这个问题。

我的解决方案:

@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, 
property = "@class")
public class Property implements IProperty, Serializable {
private static final long serialVersionUID = 1L;
private String name;
protected Property(){}

public class PropertyEnum extends Property {
private static final long serialVersionUID = 1L;
@JsonProperty
private String value;
private Collection<String> values = new LinkedList<String>();
protected PropertyEnum(){}

最新更新