[英]Deserializing a derived class using Jackson java
I have a base class as follows: 我有一个基类如下:
public class Criteria {
private CriteriaType type;
//getters & setters
public enum CriteriaType {
Condition, Medication
}
}
and derived classes 和派生类
public class ConditionCriteria extends Criteria {
private String a;
//getters & setters
}
public class MedicationCriteria extends Criteria {
private String b;
//getters & setters
}
and another class 和另一类
public class CriteriaGroup {
Criteria criteria;
//getters & setters
}
I send a serialized JSON string of CriteriaGroup
class to the server using Jackson for (de)serialialization. 我使用Jackson进行(反)序列化,将
CriteriaGroup
类的序列化JSON字符串发送到服务器。 And the service on the server looks like: 服务器上的服务如下所示:
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createCriteriaGroup(CriteriaGroup criteriaGroup) {...
However, JAckson does not convert the deserialized JSON to one of the derived classes. 但是,JAckson不会将反序列化的JSON转换为派生类之一。 How can I achieve this mapping according to the
type
field of Criteria
class? 如何根据
Criteria
类的type
字段实现此映射?
Thanks.. 谢谢..
I get an exception like this when deserializing a JSON of ConditionCriteria: 当反序列化ConditionCriteria的JSON时,我得到一个类似的异常:
SEVERE: The exception contained within MappableContainerException could not be mapped to a response, re-throwing to the HTTP container
org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "a" (Class Criteria), not marked as ignorable
at [Source: org.eclipse.jetty.server.HttpInput@3c92218c; line: 1, column: 92] (through reference chain: CriteriaGroup["criteria"]->Criteria["a"])
at org.codehaus.jackson.map.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:53)
at org.codehaus.jackson.map.deser.StdDeserializationContext.unknownFieldException(StdDeserializationContext.java:267)
.... ....
You will need to add @JsonTypeInfo
in Criteria
to enable use of additional type information, to support polymorphic types. 您将需要在
Criteria
添加@JsonTypeInfo
以启用附加类型信息的使用,以支持多态类型。 You should be able to find example of that (just google for "jackson JsonTypeInfo"). 您应该能够找到该示例(仅Google用“ jackson JsonTypeInfo”表示)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.