Home  >  Article  >  Java  >  How to Deserialize JSON into Generic Types with Jackson?

How to Deserialize JSON into Generic Types with Jackson?

DDD
DDDOriginal
2024-11-23 13:23:11467browse

How to Deserialize JSON into Generic Types with Jackson?

Generic Deserialization with Jackson

When deserializing JSON data into a generic class like Data, it's often necessary to specify the type of the generic parameter T. The standard approach using mapper.readValue(jsonString, Data.class) doesn't provide this information.

To address this, Jackson relies on the TypeReference object. By creating a TypeReference specifically for the desired generic type, you can guide the deserialization process.

To deserialize a JSON string into an instance of Data, instantiate a TypeReference using anonymous inner class syntax:

TypeReference<Data<String>> typeRef = new TypeReference<Data<String>>() {};

Then, pass the TypeReference as the second argument to the readValue method:

Data<String> data = mapper.readValue(jsonString, typeRef);

This approach ensures that Jackson knows the specific type of T to deserialize into, resulting in correct deserialization behavior.

The above is the detailed content of How to Deserialize JSON into Generic Types 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