Home > Java > javaTutorial > body text

How Can Jackson Deserialize JSON into Generic Classes?

Susan Sarandon
Release: 2024-11-21 07:18:10
Original
250 people have browsed it

How Can Jackson Deserialize JSON into Generic Classes?

Deserializing JSON into Generic Classes with Jackson

When working with JSON data, we may encounter scenarios where we need to deserialize JSON strings into classes with generic parameters. The Jackson library provides a way to handle such deserialization scenarios effectively.

To deserialize a JSON string into a generic class, we first need to define the class with the generic type parameter:

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

Now, to deserialize JSON into an instance of Data, we can use the TypeReference class provided by Jackson. The TypeReference allows us to specify the type of the generic class and deserialize the JSON accordingly.

ObjectMapper mapper = new ObjectMapper();
String jsonString = "...";

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

In this example, we create a TypeReference for Data and pass it as the second argument to readValue. Jackson will then deserialize the JSON string into an instance of Data.

It's important to note that we need to provide the specific type of the generic parameter when using TypeReference. In this case, we have specified String as the type for T.

By utilizing TypeReference, we can effectively deserialize JSON into generic classes with Jackson, allowing us to handle complex data structures with ease.

The above is the detailed content of How Can Jackson Deserialize JSON into Generic Classes?. 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