Jackson - 在 DTO 属性中建模列表映射的最佳方法是什么,其中列表键是灵活的并且列表可能作为单个单词到达?

问题描述 投票:0回答:0

我正在使用一个 REST API,它返回一组对象,其中包含一个灵活的“属性”元素,该元素在返回数据的方式上非常松散。例如,API 可能会返回一个 CharacterProfiles 集合,如下所示:

[
    {
        "id": "another523somminguid",
        "name": "Stan Smith",
        "attributes": {
            "occupation": "CIA Agent",
            "description": "A very opinionated agent with a very large chin"
        }
    },
    {
        "id": "some123abcguid",
        "name": "Roger Smith",
        "attributes": {
            "appearance": [
                "alien",
                "pear-shaped",
                "bulbous head"
            ],
            "abilities": [
                "costume design",
                "super speed"
            ]
        }
    },
    {
        "id": "299anotherguid",
        "name": "Steve Smith",
        "attributes": {
            "appearance": [
                "bespectacled",
                "skinny",
                "brown hair"
            ],
            "abilities": "no notable abilities"
        }
    }
]

看到

attributes
属性采用相当松散的形式,实际上不可能提前知道 all 键,只真正知道它们是字符串,我选择构建 DTO 以接受列表映射如下:

import java.util.Collection;
import java.util.Map;

import lombok.Data;
import lombok.Builder;
import lombok.NoArgsConstructor;
import lombok.AllArgsConstructor;

import com.fasterxml.jackson.annotation.JsonFormat;

@NoArgsConstructor
@AllArgsConstructor
public @Data @Builder class CharacterProfile {
    String id;
    String name;
    // How do I specify this format to accept the wide variety of JSON objects?
    @JsonFormat(with = what_feature?)
    Map<String, Collection<String>> attributes;
}

我在 Jackson JavaDocs 中选择

@JsonFormat
注释告诉我使用
JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY
功能可能有效,但每个参考资料都表明这仅适用于实现
Collection
接口的对象。

我需要重新考虑我的设计吗?还是我可以应用其他一些神奇的注释来将这些结构正确反序列化为可用的 DTO?如何将这些变体类型正确加载到(大部分)静态类型的 DTO 中?

java dictionary collections jackson dto
© www.soinside.com 2019 - 2024. All rights reserved.