Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read embedded object in Jackson

Tags:

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.

like image 481
Crozin Avatar asked Apr 05 '12 21:04

Crozin


People also ask

How does Jackson read nested JSON?

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.

How do I map nested values with Jackson?

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.

How do I read JSON file with ObjectMapper?

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);

What is JsonProperty annotation?

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.


1 Answers

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; } 
like image 93
Bruno Hansen Avatar answered Sep 18 '22 07:09

Bruno Hansen