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?
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'}}
What you need is a custom deserializer. Jackson How-To: Custom Deserializers
For your use case it could be something like this:
class CustomerDeserializer extends JsonDeserializer<Customer>
{
public Customer deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException, JsonProcessingException
{
JsonNode node = p.getCodec().readTree(p);
String code = node.get("code").asText();
String city = node.get("city").asText();
String street = node.get("street").asText();
Address adr = new Address(city, street);
return new Customer(code, adr);
}
}
Your JSON object for a customer should look like this:
{
"code":"C001",
"address":{
"city": "Pune",
"street": "ABC Road"
}
}
Without some additional transformation this json structure can't be mapped to two classes. Either write a class CustomerAddress
that will be having all three fields from json and then create Address getAddress()
and Customer getCustomer()
in it or transform the json to nest the address information inside the customer field as suggested by @eztam.
public CustomerAddress {
private String code;
private String city;
private String street;
public Address getAddress() {
return new Address(city, street);
}
public Address getCustomer() {
return new Customer(code, this.getAddress());
}
}
Try this !!!
{
"code":"customer1",
"address":{
"type":"nested",
"properties":{
"city":"Hyderabad",
"street":"1000ftRoad"
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.