我有以下课程:
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;
}
}
问题是,现在我可以将两个类都转换为EventB
,并将type=="eventA"
与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);
有没有办法将json中type
字段的值与你试图解析的类中type
的默认值进行比较,如果不匹配就抛出异常?
1条答案
按热度按时间jk9hmnmh1#
在我看来,最好的解决方案是自定义格式化,这样:
事件解析器
EventDeserializer
根据type
字段自动检查类型。要使其工作,您需要更改类中的注解。这样:
事件
@JsonDeserialize
注解指定了自定义解析器类。所以现在你不需要
@JsonCreator
和@JsonProperty
注解:事件A
事件B
现在,如果你尝试用
type == "eventA"
的JSON示例化一个EventB
,它将抛出一个java.lang.ClassCastException
:我希望它有帮助:)