我的库正在调用一个 API,它可以返回以下 JSON 结构之一 -
{
"key_is_same" : {
"inner" : "val"
}
}
-或-
{
"key_is_same" : [{
"inner" : "val1"
},
{
"inner" : "val2"
}
]
}
jakson 中是否有任何注释可以处理此问题并将其反序列化为相应的类型
最佳答案
您似乎正在寻找 ACCEPT_SINGLE_VALUE_AS_ARRAY
反序列化功能。
Feature that determines whether it is acceptable to coerce non-array (in JSON) values to work with Java collection (arrays,
java.util.Collection
) types. If enabled, collection deserializers will try to handle non-array values as if they had "implicit" surrounding JSON array. This feature is meant to be used for compatibility/interoperability reasons, to work with packages (such as XML-to-JSON converters) that leave out JSON array in cases where there is just a single element in array.Feature is disabled by default.
它可以在ObjectMapper
中启用:
ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
或通过 @JsonFormat
注释:
@JsonFormat(with = Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
private List<Foo> oneOrMany;
<小时/>
出于说明目的,请考虑以下 JSON 文档:
{
"oneOrMany": [
{
"value": "one"
},
{
"value": "two"
}
]
}
{
"oneOrMany": {
"value": "one"
}
}
它可以反序列化为以下类:
@Data
public class Foo {
private List<Bar> oneOrMany;
}
@Data
public class Bar {
private String value;
}
只需确保在您的 ObjectMapper
中启用该功能,或者您的字段使用 @JsonFormat(with = Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY) 进行注释
。
如果您正在寻找等效的序列化功能,请参阅 WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED
.
关于java - 使用 Jackson 反序列化一个属性,该属性可以是对象列表或对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58104362/