Home >Java >javaTutorial >How to Deserialize JSON into a Generic Class with Jackson?

How to Deserialize JSON into a Generic Class with Jackson?

DDD
DDDOriginal
2024-11-20 11:41:19618browse

How to Deserialize JSON into a Generic Class with Jackson?

Deserializing JSON using Generic Types with Jackson

Question: How to deserialize JSON data into a generic class using Jackson?

Consider the following example class:

class Data<T> {
    int found;
    Class<T> hits
}

A standard JSON deserialization attempt using mapper.readValue(jsonString, Data.class) will fail. To correctly deserialize the data, we need to specify the type parameter .

Answer: Jackson provides a TypeReference class to handle generic types during deserialization. To use it:

  1. Create a TypeReference object for the generic class. In this example, the type reference for Data would be:

    new TypeReference<Data<String>>() {}
  2. Pass the TypeReference object to the readValue method:

    mapper.readValue(jsonString, new TypeReference<Data<String>>() {});

This will correctly deserialize the JSON data into an instance of Data.

The above is the detailed content of How to Deserialize JSON into a Generic Class with Jackson?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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