通过特定的 json 键名继承 Jackson

Inheritance with Jackson by specific json key name

我有这个 json:

{
  "fields": [
    {"expression": "count(*)"},
    {"column": "field1"},
  ]
}

我想使用继承。我创建了 classes:

@JsonTypeInfo(
        use = JsonTypeInfo.Id.NAME)
@JsonSubTypes({
        @JsonSubTypes.Type(value = Expression.class, name = "expression"),
        @JsonSubTypes.Type(value = Field.class, name = "column")})
public abstract class TargetClause {
}

表达式:

public class Expression extends TargetClause {

    @JsonProperty("expression", required = true)
    String expression;
}

字段:

public class Field extends TargetClause {

    @JsonProperty(value = "column", required = true)
    String column;
}

和包装器对象: public class 包装器 {

@JsonProperty(value = "fields", required = true)
List<TargetClause> fields;

}

但是,它对我不起作用。我得到错误:

Caused by: com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Missing type id when trying to resolve subtype of [simple type, class TargetClause]: missing type id property '@type' (for POJO property 'fields')

但是,我不想在我的 json 中添加任何字段。我想让jackson通过json中的键名来了解这个对象属于什么类型的对象。如果是expression => Expression class,如果是column => Field class。如何做到这一点?

其中一个选项是使用基于 属性 表达式或列的自定义反序列化程序。

请检查https://github.com/FasterXML/jackson-databind/issues/1627