Serialise/deserialise wrapper with List<Message<TData>> in Jackson

Viewed 18

I'm trying to do something like https://github.com/brharrington/jackson-databind/blob/master/src/test/java/com/fasterxml/jackson/databind/ser/TestGenericTypes.java#L10 but with a twist. How can I serialise and deserialise an object graph like this?

public class Envelope {
    // more fields here


    // CRUX IS HERE; I can't type it as List<BaseMessage<>> unfortunately
    public List<BaseMessage<Object>> payload;


}

@JsonTypeInfo(
        use = JsonTypeInfo.Id.NAME,
        include = JsonTypeInfo.As.PROPERTY,
        property = "n"
)
@JsonSubTypes({
        @JsonSubTypes.Type(value = AMessage.class, name = "a"),
        @JsonSubTypes.Type(value = BMessage.class, name = "b"),
})
public abstract class BaseMessage<TData> {
    // discriminator field getters and setters (no abstract field in Java)
    public abstract String getN();
    public abstract void setN(String n);
    // more props
    public TData ps;
    public SpanContext s;
}
public class AMessage extends BaseMessage<MessageData> {
    public String n = "a";

    @Override
    public String getN() {
        return n;
    }

    @Override
    public void setN(String n) {
        this.n = n;
    }
}
public class MessageData {
    public String example;
    // more props
}
public class BMessage extends BaseMessage<MessageData> {
    public String n = "b";

    @Override
    public String getN() {
        return n;
    }

    @Override
    public void setN(String n) {
        this.n = n;
    }
}
  1. I'd be happiest if I can configure this with jackson annotations
  2. Secondly, if I can use TypeReference in some way
  3. Thirdly, if I can type the list as List<JsonValue> and subsequently call jackson explicitly by reading the discriminator field n manually and then calling jackson with the actual type
1 Answers

The code above is correct from the start; you'll have to use runtime reflection to check what the type of the <Object> is.

Related