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

How Can I Deserialize JSON into a Generic Class with Jackson?

DDD
Release: 2024-11-19 01:35:03
Original
721 people have browsed it

How Can I Deserialize JSON into a Generic Class with Jackson?

Generic Class Deserialization with Jackson

When attempting to deserialize JSON data into a generic class like Data, the question arises as to how to specify the type parameter T. The typical approach of using mapper.readValue(jsonString, Data.class) only constructs an instance of Data, but the specific type of T remains unknown.

Solution

Jackson provides a solution through the TypeReference class. By creating a TypeReference object for the desired generic type and passing it to the readValue method, we can explicitly specify the type parameter.

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

In this example, a TypeReference is created for the generic class Data, ensuring that the deserialized object will be an instance of Data with T set to String.

The above is the detailed content of How Can I 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