Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson Deserialization of Embedded Java Object

I have to deserialize following json using Jackson library into Customer class

{
   "code":"C001",
   "city": "Pune",
   "street": "ABC Road"
}

and Classes as

class Address{
    String city;
    String street;
}

class Customer{
    String code;
    Address address;
}

I have found similar question on stack Java jackson embedded object deserialization

but answer does not apply to my case. Also I only want to use Jackson library.

How can I map this json to Customer object?

like image 632
vijay Avatar asked Feb 26 '16 10:02

vijay


People also ask

Does Jackson use Java serialization?

Note that Jackson does not use java.

What is Jackson deserialization?

Jackson is a powerful and efficient Java library that handles the serialization and deserialization of Java objects and their JSON representations. It's one of the most widely used libraries for this task, and runs under the hood of many other frameworks.

How does ObjectMapper work in Java?

The Jackson ObjectMapper can parse JSON from a string, stream or file, and create a Java object or object graph representing the parsed JSON. Parsing JSON into Java objects is also referred to as to deserialize Java objects from JSON. The Jackson ObjectMapper can also create JSON from Java objects.


1 Answers

You can put a @JsonUnwrapped annotation on the Address field in the customer class. Here is an example:

public class JacksonValue {
    final static String JSON = "{\n"
            +"   \"code\":\"C001\",\n"
            +"   \"city\": \"Pune\",\n"
            +"   \"street\": \"ABC Road\"\n"
            +"}";

    static class Address {
        public String city;
        public String street;

        @Override
        public String toString() {
            return "Address{" +
                    "city='" + city + '\'' +
                    ", street='" + street + '\'' +
                    '}';
        }
    }

    static class Customer {
        public String code;
        @JsonUnwrapped
        public Address address;

        @Override
        public String toString() {
            return "Customer{" +
                    "code='" + code + '\'' +
                    ", address=" + address +
                    '}';
        }
    }


    public static void main(String[] args) throws IOException {
        final ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.readValue(JSON, Customer.class));
    }
}

Output:

 Customer{code='C001', address=Address{city='Pune', street='ABC Road'}}
like image 158
Alexey Gavrilov Avatar answered Sep 24 '22 11:09

Alexey Gavrilov