Home > Java > javaTutorial > body text

How to Deserialize JSON into a Generic Class with Jackson?

DDD
Release: 2024-11-20 11:41:19
Original
551 people have browsed it

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
}
Copy after login

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>>() {}
    Copy after login
  2. Pass the TypeReference object to the readValue method:

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template