I need to deserialize a flat JSON object to a Java object with some properties set to child object.
{
"name": "abcd",
"addressLine1": "123",
"addressLine2": "1111"
}
Class Student {
String name;
Address address;
}
Class Address {
String line1;
String line2;
}
How do I deserialize my JSON using Jackson into a Student object?
I am not able to map addressLine1 to Student.Address.line1
and addressLine2 to Student.Address.line2
You can define your data classes this way:
public static class Student {
String name;
@JsonUnwrapped
Address address;
}
public static class Address {
@JsonProperty("addressLine1")
String line1;
@JsonProperty("addressLine2")
String line2;
}
Then you can use the Objectmapper in the usual way - without any additional magic or workaround :
Student student = mapper.readValue(json, Student.class);
If your incoming json string is indeed in the format you provided (without quotes) then also add:
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
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