1

I'm using Jackson to try and deserialize this data structure:

{
  "type": "foo",       // or "bar", "baz", etc
  "name": "number 1",
  "params": {
    // parameters specific to type 'foo'
  }
}

I know I could use a custom deserializer, but I'm wondering if this is possible to do using just the @JsonType* family of annotations?

Right now I have my classes set up something like this:

public class TopLevelObject {
    String type;
    String name;
    AbstractParams params;
}

public class FooParams extends AbstractParams {
    String one;
    String two;
}

public class BarParams extends AbstractParams {
    String three;
    String four;
}

abstract public class AbstractParams {
}

I can use @JsonTypeInfo on the type property if I move the property into the AbstractParams class, but I can't seem to get the same result while keeping the type property in the TopLevelObject.

Any ideas?

1 Answers1

0

Can use @JsonTypeInfo(use = Id.NAME, include = As.EXTERNAL_PROPERTY). But As.EXTERNAL_PROPERTY can only be used for properties. More info.

So you have to put @JsonTypeInfo annotation on the AbstractParams field/setter of the TopLevelObject class

class TopLevelObject {
    public String type;
    public String name;

    @JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
            include= JsonTypeInfo.As.EXTERNAL_PROPERTY,
            property = "type")
    @JsonSubTypes({
            @JsonSubTypes.Type(value = FooParams.class, name = "foo"),
            @JsonSubTypes.Type(value = BarParams.class, name = "bar")})
    public AbstractParams params;

}
varren
  • 14,551
  • 2
  • 41
  • 72