cgsd
cgsd

Reputation: 1333

Serializing generic type with Jackson and @JsonTypeInfo

I have the following class:

@JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME,
    include = JsonTypeInfo.As.PROPERTY,
    property = "type"
)
@JsonSubTypes({
    @JsonSubTypes.Type(value = CardOne.class, name = "CARD_ONE")
})
public abstract class Card {
    String type;

    // Getters & Setters
}

public class CardOne extends Card {
  String foo;

  // Getters & Setters
}

And the following JSON string will serialize no problem into it.

{
  "type": "CARD_ONE",
  "foo": "bar"
}

How do I make this work if I instead want to use composition with a generic type? I want something like this:

public class Card<T> {
    String type;
    T cardProperties();

   // Getters & Setters
}

public class CardOneProperties {
  String foo;

  // Getters & Setters
}

Upvotes: 1

Views: 2780

Answers (1)

rahul margam
rahul margam

Reputation: 51

Because of type erasure in java the byte code has no information of the parameterized type of card. You could try the solution referenced here. It Illustrates how you would serialize a List object of parameterized type.

https://stackoverflow.com/a/6852184/9814390

Upvotes: 1

Related Questions