I'm trying to read a legacy JSON code using Jackson 2.0-RC3, however I'm stuck with an "embedded" object.
Given a following JSON:
{ "title": "Hello world!", "date": "2012-02-02 12:23:34". "author": "username", "author_avatar": "http://.../", "author_group": 123, "author_prop": "value" }
How can I map it into the following structure:
class Author { @JsonPropery("author") private String name; @JsonPropery("author_avatar") private URL avatar; @JsonProperty("author_group") private Integer group; ... } class Item { private String title; @JsonProperty("date") private Date createdAt; // How to map this? private Author author; }
I was trying to do that with @JsonDeserialize
but it seems that I'd have to map the entire Item
object that way.
A JsonNode is Jackson's tree model for JSON and it can read JSON into a JsonNode instance and write a JsonNode out to JSON. To read JSON into a JsonNode with Jackson by creating ObjectMapper instance and call the readValue() method. We can access a field, array or nested object using the get() method of JsonNode class.
To map the nested brandName property, we first need to unpack the nested brand object to a Map and extract the name property. To map ownerName, we unpack the nested owner object to a Map and extract its name property.
Read Object From JSON via URL ObjectMapper objectMapper = new ObjectMapper(); URL url = new URL("file:data/car. json"); Car car = objectMapper. readValue(url, Car. class);
The @JsonProperty annotation is used to map property names with JSON keys during serialization and deserialization. By default, if you try to serialize a POJO, the generated JSON will have keys mapped to the fields of the POJO.
To deal with an "embedded" object you should use @JsonUnwrapped
— it's an equivalent of the Hibernate's @Embeddable
/@Embedded
.
class Item { private String title; @JsonProperty("date") private Date createdAt; // How to map this? @JsonUnwrapped private Author author; }
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