Search code examples
jsonaliasxstreamdata-conversion

Any JSON to Object converter that has alias for multiple classes?


I have found JETTISON driver to meet my needs.

But for some reason, while using ArrayList it is working in my local testing but not when deployed in my jboss server. (I will ask this an as another question)

Are there any other? I have already tried with GSON and Jackson, but does not help.

This is the structure that i need:

class A
{
    List<A> memberList;
}

class B extends A

class C,D extends class A

I have an object of class B, which contains instances of class C & D.

If i use GSON or Jackson, when the object of class B is converted to JSON, it loses the class type of C & D. Hence, when i convert it back to an object, i cannot find whether the list memberList contains objects of type C or D.

Please help!


Solution

  • I've found a way that use jackson. very nice explanation here

    Basically, for the above example, i'll have to provide a notation for class A as follows:

    import com.fasterxml.jackson.annotation.JsonSubTypes;
    import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
    import com.fasterxml.jackson.annotation.JsonTypeInfo;
    import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;
    
    @JsonTypeInfo(use = Id.CLASS,
                  include = JsonTypeInfo.As.PROPERTY,
                  property = "type")
    @JsonSubTypes({
        @Type(value = C.class),
        @Type(value = D.class),
        })