简体   繁体   中英

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.

You can accomplish this using the following Jackson annotations:

class Hello {
    @JsonUnwrapped
    private ListWrapper list;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM