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?
Note that Jackson does not use java.
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.
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.
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'}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With