Curro
Curro

Reputation: 1411

Jackson Polymorphic Deserialization based on Enum

I'm working with JacksonPolymorphicDeserialization, this is my code which deserializes into the proper class based in the 'type' property:

@JsonTypeInfo(  
    use = JsonTypeInfo.Id.NAME,  
    include = JsonTypeInfo.As.PROPERTY,  
    property = "type",
    defaultImpl = Event.class, 
    visible = true)  
@JsonSubTypes({        
    @Type(value = SpecialEvent1.class, name = "SPECIAL_EVENT_1"), 
    @Type(value = SpecialEvent2.class, name = "SPECIAL_EVENT_2"), 
    })  
public abstract class AbstractEvent {

    private String type;

    public String getType() {
    return type;
    }

    public void setType(String type) {
    this.type = type;
    }   
}

It's working perfectly and my json turns into the expected class according to the 'type' value.

However, I'm considering to move the 'type' property from String to Enum, this is my new code with this change:

@JsonTypeInfo(  
    use = JsonTypeInfo.Id.NAME,  
    include = JsonTypeInfo.As.PROPERTY,  
    property = "type",
    defaultImpl = Event.class, 
    visible = true)  
@JsonSubTypes({        
    @Type(value = SpecialEvent1.class, name = "SPECIAL_EVENT_1"), 
    @Type(value = SpecialEvent2.class, name = "SPECIAL_EVENT_2"), 
    })  
public abstract class AbstractEvent {

    private EventType type;

    public EventType getType() {
    return type;
    }

    public void setType(EventType type) {
    this.type = type;
    }   
}

and the Enum:

public enum EventType {
    SPECIAL_EVENT_1,
    SPECIAL_EVENT_2,
    EVENT;
}

The problem is that this second approach is not working... any idea why??? can I use Enum here???

Thanks!

Upvotes: 48

Views: 26071

Answers (2)

Souf KMD
Souf KMD

Reputation: 199

It worked for me using enum with the following :

@JsonTypeInfo(  
    use = JsonTypeInfo.Id.NAME,  
    include = JsonTypeInfo.As.EXISTING_PROPERTY,  
    property = "type",
    visible = true
) 

Upvotes: 13

Curro
Curro

Reputation: 1411

Fixed!

It works with jackson 2.0!!

Upvotes: 28

Related Questions