简体   繁体   中英

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. 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. How can I achieve this mapping according to the type field of Criteria class?

Thanks..

I get an exception like this when deserializing a JSON of ConditionCriteria:

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. You should be able to find example of that (just google for "jackson JsonTypeInfo").

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM