Jackson Polymorphic de-serializing primitive types

Viewed 374

I'm using Jackson 1.9.13 and have the following simple classes to serialize/de-serialize

public interface Comparable {
    //interfaces definition
}

public class ComparableString implements Comparable {
    protected String member;

    //Constructor and interface implementation etc.

    @JsonValue
    public String getString() { return this.member; }
}

//Many other comparables

public class Checker {
    private Comparable left;
    private Comparable right;
    //Getters & Setters

    public Checker(Comparable left, Comparable right) {
    }
}

Now that I constructed such one Checker with two ComparableString (whose values are "A" and "B") and want to serialize it, it works perfectly fine and gives me, e.g.

{"left":"A", "right":"B"}

But now I want to de-serialize it, it tells me: Can not construct instance of Comparable, problem: abstract types can only be instantiated with additional type information.

I understand that it couldn't determine which concrete type should it use when it sees Comparable. So I additionally annotated Comparable interface like this:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY, defaultImpl = ComparableString.class)
@JsonSubTypes({
    @JsonSubTypes.Type(value = ComparableString.class)
    //other comparable types
})
public interface Comparable {
    //interfaces definition
}

But now it requires additional type field when de-serialization a primitive (who apparently doesn't have any additional type information around it), and serialization changes too, it becomes something like this:

{
    "left":["ComparableString","A"],
    "right":["ComparableString","B"]
}

I tried to specify use = JsonTypeInfo.Id.NONE then it goes back to the unable to identify which type it is error. Apparently, without the type info around, it couldn't determine which type exactly to use to de-serialize a primitive.

My question is: is it possible to somehow manually mapping primitive de-serialization into one of the Comparable classes? Without sacrificing the simplicity of primitives (no additional field for type in JSON body).

0 Answers
Related