我正在使用一个 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;
}
@JsonFormat
注释告诉我使用 JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY
功能可能有效,但每个参考资料都表明这仅适用于实现 Collection
接口的对象。
我需要重新考虑我的设计吗?还是我可以应用其他一些神奇的注释来将这些结构正确反序列化为可用的 DTO?如何将这些变体类型正确加载到(大部分)静态类型的 DTO 中?