DCestLaVie
DCestLaVie

Reputation: 61

Jackson: How to deserialize a list into the value of a field

I am using Jackson as a tool to deserialize a input JSON into a Java POJO. However, I have the need to deserialze a list value into a field of a wrapper class. Here is a sample code:

class Hello {
    private ListWrapper list;
}

class ListWrapper {
    private List<Item> unnamed;
}

class Item {
    // some fields
}

If the user input is as follow, I would like it to be deserialized into a Hello instance with "list" field containing a ListWrapper instance whose "unnamed" field holding the items.

{
    "list": [
        {
            // item1
        }
        {
            // item2
        }
    ]
}

Note that I don't want to customize a deserializer that is used by @JsonDeserialize, because I want Jackson to do the mapping validation on Item for me.

Is it possible? And How?

Thanks.

Upvotes: 0

Views: 753

Answers (1)

ck1
ck1

Reputation: 5443

You can accomplish this using the following Jackson annotations:

class Hello {
    @JsonUnwrapped
    private ListWrapper list;
}

class ListWrapper {
    @JsonProperty("list")
    private List<Item> unnamed;
}

Upvotes: 1

Related Questions