2

//interface

public interface NotificationPayload {
}

//Classes implement interface

public ClassA implements NotificationPayload {...}
public ClassB implements NotificationPayload {...}
...
public ClassX implements NotificationPayload {...}

//Message to send

public class Notification<T extends NotificationPayload> {
    private T data; //T may be ClassA/ClassB/ClassC.../ClassX
    ...
}

When I receive a message as a json, I want to convert it to Notification again by using ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)

json example:

{
    "type":"ClassA",
    "userId":10087
}

I convert it:

Notification notif = objectMapper.readValue(json, Notification.class);

it throw exception:

java.lang.IllegalArgumentException: Can not construct instance of 
com.common.kafka.notification.NotificationPayload: abstract types
either need to be mapped to concrete types, have custom deserializer, or
contain additional type information
at [Source: N/A; line: -1, column: -1] (through reference chain:
com.common.kafka.notification.Notification["data"])

I had read from this question: Cannot construct instance of - Jackson but seem like It cannot help because I have too many Class implement from interface, not only once.

Loc Le
  • 537
  • 1
  • 8
  • 21

1 Answers1

2

You need to use jackson's annotation to achieve polymorphic deserialization.

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
        include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({
        @JsonSubTypes.Type(value = ClassA.class, name = "ClassA"),
        @JsonSubTypes.Type(value = ClassB.class, name = "ClassB")
})
public interface NotificationPayload {
}

public class ClassA implements NotificationPayload {

    private Integer userId;

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }
}

public class Notification <T extends NotificationPayload> {

    private T data; //T may be ClassA/ClassB/ClassC.../ClassX

    @JsonCreator
    public Notification(T data) {
        this.data = data;
    }

    public static void main(String[] args) throws IOException {

        String jsonStr = "{\"type\":\"ClassB\",\"userId\":10087}";

        ObjectMapper objectMapper = new ObjectMapper();
        Notification notification = objectMapper.readValue(jsonStr, Notification.class);
    }
}

All the annotations you can find here

dai
  • 1,025
  • 2
  • 13
  • 33