How do you handle polymorphic types in Jackson?

How do you handle polymorphic types in Jackson?

A) By using the @JsonTypeInfo annotation
B) By using the @JsonSubTypes annotation
C) By using the @JsonProperty annotation
D) By using the @JsonIgnoreProperties annotation

Answer:

A) By using the @JsonTypeInfo annotation

Explanation:

In Jackson, you can handle polymorphic types (where an object can be of multiple types) using the @JsonTypeInfo annotation. This annotation allows you to include type information in the JSON output and input, enabling Jackson to deserialize the correct subtype of a polymorphic object.

For example:


@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 { ... }

public class Cat extends Animal { ... }
public class Dog extends Animal { ... }

In this example, the @JsonTypeInfo annotation is used to include a “type” property in the JSON, which helps Jackson determine whether the object should be deserialized as a Cat or a Dog.

Reference links:

https://www.javaguides.net/p/top-java-libraries.html

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top