Read embedded object in Jackson

Crozin picture Crozin · Apr 5, 2012 · Viewed 14.2k times · Source

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.

Answer

Bruno Hansen picture Bruno Hansen · Apr 9, 2012

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