Jackson JSON Deserialization with Root Element

Jackson JSON Deserialization with Root Element

In Jackson, you can deserialize JSON data that has a root element by using a wrapper class and annotations to specify the root element's name. This is often referred to as "wrapped" or "root element" deserialization. Here's how you can do it:

Let's assume you have JSON data like this:

{ "person": { "id": 1, "name": "John" } } 

And you want to deserialize it into a Java object with a root element named "person."

  1. Create Java Classes:

    First, create the Java classes that represent the structure of the JSON data.

    import com.fasterxml.jackson.annotation.JsonRootName; @JsonRootName("person") public class Person { private int id; private String name; // Getters and setters } 

    The @JsonRootName annotation is used to specify the root element name.

  2. Deserialize JSON:

    Use Jackson's ObjectMapper to deserialize the JSON data into the Java object.

    import com.fasterxml.jackson.databind.ObjectMapper; public class Main { public static void main(String[] args) throws Exception { String json = "{\"person\":{\"id\":1,\"name\":\"John\"}}"; ObjectMapper objectMapper = new ObjectMapper(); Person person = objectMapper.readValue(json, Person.class); System.out.println("ID: " + person.getId()); System.out.println("Name: " + person.getName()); } } 

    In this example, we deserialize the JSON data into an instance of the Person class.

By using the @JsonRootName annotation and specifying the root element name, you can deserialize JSON data with a root element into a corresponding Java object. Make sure you have the Jackson library added to your project's dependencies to use these annotations and perform JSON serialization/deserialization.


More Tags

maxlength android-bottomappbar jmeter-5.0 xpath iis-7 basic out-of-memory file-handling whatsapp sdp

More Java Questions

More Financial Calculators

More Chemical thermodynamics Calculators

More Investment Calculators

More Biology Calculators