Deserialization of embedded Java objects
•
Java
I have to deserialize the following JSON to use the Jackson library to enter the client 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 a similar problem on the stack: Java Jackson embedded object deserialization
But the answer doesn't apply to me Besides, I just want to use the Jackson library
How do I map this JSON to a customer object?
Solution
You can add a @ jsonunwrapped comment in the address field of 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'}}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码