Search code examples
javajsonjacksonjackson-databind

Inheritance with Jackson by specific json key name


I have this json:

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

I want use inheritance. I created 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 {
}

Expression:

public class Expression extends TargetClause {

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

Field:

public class Field extends TargetClause {

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

And wrapper object: public class Wrapper {

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

}

But, It don't work for me. I get error:

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

But, I don't want add any field im my json. I want jackson to understand what type of object this object belongs to by using the key name in json. If it is expression => Expression class, if column => Field class. How can this be done?


Solution

  • one of the options will be to use custom deserializer based on the property expression or column.

    Please check https://github.com/FasterXML/jackson-databind/issues/1627