I have the following classes:
public abstract class Event {
private final String eventId;
public Event(String eventId) {
this.eventId = eventId;
}
}
public class EventA extends Event {
private final String type = "eventA";
@JsonCreator
public EventA(@JsonProperty("eventId") String eventId) {
super(eventId);
}
public String getType() {
return type;
}
}
public class EventB extends Event {
private final String type = "eventB";
@JsonCreator
public EventB(@JsonProperty("eventId") String eventId) {
super(eventId);
}
public String getType() {
return type;
}
}
Problem is now I can deserialize to both classes and have an EventB
with type=="eventA"
:
EventA eventA = new ObjectMapper().readValue(
"{\"gameProposalId\":\"foo\", \"type\": \"eventA\"}",
EventA.class);
// This will result in EventB with type=="eventA"
EventB eventB = new ObjectMapper().readValue(
"{\"gameProposalId\":\"foo\", \"type\": \"eventA\"}",
EventB.class);
Is there a way to instead compare the value of the type
field in the json to the default value of type
in the class you are trying to deserialize to, and throw an exception if they don't match?