Bick
Bick

Reputation: 18551

Java Jackson : Can I hold in a json the type to deserialize it to?

the usual way to serialize to json and back is:

String catStr = mapper.writeValueAsString(cat);
Cat catOut = mapper.readValue(catStr, Cat.class);

Is there a way to add (maybe with annotation ) the type to the json on serialization and let the mapper take the value from it when it deserialize it?

so I can do the following

Object obj = mapper.readValue(catStr);

and later...

Cat catOut = (Cat)obj; 

Thanks.

Upvotes: 1

Views: 220

Answers (1)

Uri Shalit
Uri Shalit

Reputation: 2318

Sort of. You can add a property to the serialization which will indicate what class it is. And then when deserializing it, Jackson deduces the class automatically.

But you cannot deserialize it as Object, you need some base class/interface for all objects you want to behave like this. And that interface needs to use the @JsonTypeInfo annotation, signalling Jackson when deserializing this base class use the property class to distinguish which type.

Example:

@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY)
private abstract class Base {

}

private class A extends Base {
    private final int i;

    @JsonCreator
    public A(@JsonProperty("i") int i) {
        this.i = i;
    }
}

When serialized will be:

{"@class":"com.test.A","i":3}

Testing code:

    A a = new A(3);
    String str = mapper.writeValueAsString(a);
    Base base = mapper.readValue(str, Base.class);

Upvotes: 2

Related Questions