I looked through many questions related to this, but I cannot find this specific use case. Suppose I use the Java Jackson library.
I have the following class hierarchy:
public class Event { @JsonProperty("si") String sessionId; @JsonProperty("eventType") String eventType; ... } @JsonSerialize(include= JsonSerialize.Inclusion.NON_NULL) public class InitEvent extends Event { @JsonProperty("pm") Params params; public Params getParams() { return params; } ..... } @JsonSerialize(include= JsonSerialize.Inclusion.NON_NULL) public class RecoEvent extends Event { @JsonProperty("ti") String targetId; @JsonProperty("tt") int targetType; public String getTargetId() { return targetId; } .... }
Deserialization rule:
If eventType == 0, then deserialize in InitEvent
If eventType == 0, then deserialize in RecoEvent
From the discharge, Jackson's deserialization will not work, because he does not know for which class to deserialize. One way to handle this is as follows: base class:
@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class") @JsonSerialize(include= JsonSerialize.Inclusion.NON_NULL) public class Event
The problem with this solution assumes that the client will serialize with the same mapper since the @class element must be present in JSON.
My client will not send an additional @class element in incoming JSON.
What is the required solution?
How can I write my own deserializer that selects the correct derived class based on the value of eventType?
thanks in advance
source share