Jackson - Deserialize using generic class

Jackson - Deserialize using generic class

You can use Jackson, a popular JSON library in Java, to deserialize JSON into a generic class by leveraging Java's TypeReference. Here's an example of how to do this:

Suppose you have a JSON string representing a list of objects:

[ { "name": "Alice", "age": 30 }, { "name": "Bob", "age": 25 } ] 

And you have a generic class Result<T> to represent the result, where T can be any class:

import java.util.List; public class Result<T> { private List<T> data; // Getter and setter for 'data' } 

You can deserialize this JSON into a Result instance with a specific type for T using Jackson like this:

import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; public class DeserializeGenericClass { public static void main(String[] args) throws Exception { String jsonString = "[{\"name\":\"Alice\",\"age\":30},{\"name\":\"Bob\",\"age\":25}]"; // Create an instance of ObjectMapper ObjectMapper objectMapper = new ObjectMapper(); // Define a TypeReference for the generic type TypeReference<Result<Person>> typeReference = new TypeReference<Result<Person>>() {}; // Deserialize the JSON into the generic class Result<Person> result = objectMapper.readValue(jsonString, typeReference); // Access the data List<Person> dataList = result.getData(); for (Person person : dataList) { System.out.println("Name: " + person.getName() + ", Age: " + person.getAge()); } } } 

In this example:

  1. We have a JSON string representing a list of people.
  2. We create an ObjectMapper instance from Jackson to perform the deserialization.
  3. We define a TypeReference<Result<Person>> that captures the generic type information of Result<Person>. Jackson uses this to deserialize the JSON into the generic class correctly.
  4. We use objectMapper.readValue(jsonString, typeReference) to deserialize the JSON string into a Result<Person> instance.
  5. Finally, we access the data in the Result instance, which is a list of Person objects.

Make sure you have the Jackson library added to your project's dependencies for this code to work. Jackson allows you to deserialize JSON into a wide range of generic types with type safety.


More Tags

latitude-longitude cpython activator prolog q multiline custom-element ini spatial-query python-3.5

More Java Questions

More Livestock Calculators

More Mixtures and solutions Calculators

More Chemical reactions Calculators

More Biochemistry Calculators