Jackson Polymorphic Deserialization based on Enum
Asked Answered
S

2

45

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!

Soviet answered 11/4, 2013 at 9:36 Comment(0)
S
27

Fixed!

It works with jackson 2.0!!

Soviet answered 11/4, 2013 at 10:32 Comment(5)
Seems if you don't put the visible to true in this case it wont work....can you confirm?Overstudy
I can confirm that visible needs to be true to work. In my case I also used include = JsonTypeInfo.As.EXISTING_PROPERTY to avoid the property appearing twice during serialization.Humidify
Thank you for the visible=true. works perfectly with enums :)Stubbed
And what about using the enum value EventType.SPECIAL_EVENT_1 instead of a String? Is it possible?Truth
@Truth No, because the name must be a constant.Polypus
E
10

It worked for me using enum with the following :

@JsonTypeInfo(  
    use = JsonTypeInfo.Id.NAME,  
    include = JsonTypeInfo.As.EXISTING_PROPERTY,  
    property = "type",
    visible = true
) 
Edelmiraedelson answered 9/6, 2020 at 8:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.