Home > Java > javaTutorial > body text

How to Deserialize Polymorphic JSON Using Jackson's ObjectMapper without Compilation Errors?

Mary-Kate Olsen
Release: 2024-11-24 16:36:11
Original
792 people have browsed it

How to Deserialize Polymorphic JSON Using Jackson's ObjectMapper without Compilation Errors?

Jackson and Polymorphic JSON: Addressing Compilation Errors for ObjectNode Deserialization

This inquiry seeks to resolve a compilation error faced when deserializing polymorphic JSON using Jackson's ObjectMapper. Specifically, the error lies in the line:

return mapper.readValue(root, animalClass);
Copy after login

Issue Explanation:

The error stems from a mismatch between the method signature of readValue() and the arguments provided. readValue() expects two arguments: a JsonParser and a Class, but in this code, an ObjectNode (not a JsonParser) and a subtype of Animal (not Animal itself) are being passed.

Annotation-Based Polymorphism Solution:

As an alternative to the registry-based approach mentioned in the tutorial, consider using Jackson's annotation-based approach for polymorphic deserialization. This involves:

  1. Annotating the Animal class: Use @JsonTypeInfo to define how type information is stored in the JSON, along with @JsonSubTypes to specify the possible subtypes.
  2. Annotating the subclasses (e.g., Dog and Cat): Use @JsonTypeId to define the name of the property that holds the type information.

Example Implementation:

// An abstract base class for animals
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY)
@JsonSubTypes({
  @JsonSubTypes.Type(value = Dog.class, name = "Dog"),
  @JsonSubTypes.Type(value = Cat.class, name = "Cat")
})
public abstract class Animal { ... }

// Subclass for dogs
public class Dog extends Animal { ... }

// Subclass for cats
public class Cat extends Animal { ... }

// Test class
public class Test {

  public static void main(String[] args) {
    ObjectMapper mapper = new ObjectMapper();
    ... // Serialize and deserialize animals as shown in the provided solution
  }
}
Copy after login

By utilizing annotations, Jackson can infer the type of the object based on the provided type information in the JSON, avoiding the need for a registry and resolving the compilation error.

The above is the detailed content of How to Deserialize Polymorphic JSON Using Jackson's ObjectMapper without Compilation Errors?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template