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:
Create a TypeReference object for the generic class. In this example, the type reference for Data
new TypeReference<Data<String>>() {}
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!