Question

I've seen an example of jackson deserialization @JsonTypeInfo, that is:

@JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME,
    include = JsonTypeInfo.As.PROPERTY,
    property = "type")
@JsonSubTypes({
    @JsonSubTypes.Type(value = Cat.class, name = "cat"),
    @JsonSubTypes.Type(value = Dog.class, name = "dog")})
public class Animal {...}

I've tried it and it works fine. Now, the problem is that in the example classes Cat and Dog are referenced from Animal, which I want to avoid. Is there a way to move type binding from class Animal and still have deserialization work? Thanks

Was it helpful?

Solution

I found an answer here: http://jira.codehaus.org/browse/JACKSON-654. So I could use:

mapper.registerSubtypes(Cat.class, Dog.class);

OTHER TIPS

It's also worth a shot removing @JsonSubTypes altogether. It's not always necessary, see https://stackoverflow.com/a/57686619/5298002

" You need only one line before the declaration of the class Animal for correct polymorphic serialization/deserialization:

@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")
public abstract class Animal {
   ...
}

This line means: add a meta-property on serialization or read a meta-property on deserialization (include = JsonTypeInfo.As.PROPERTY) called "@class" (property = "@class") that holds the fully-qualified Java class name (use = JsonTypeInfo.Id.CLASS).

So, if you create a JSON directly (without serialization) remember to add the meta-property "@class" with the desired class name for correct deserialization.

More information here " - @marco

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top