如何用Jackson解析可能是字符串也可能是数组的字段 [英] How to parse field that may be a string and may be an array with Jackson
问题描述
我是 Java 和 objectMapper 的新手.我正在尝试解析一个键可能有两种类型的 json 字段,它可以是字符串或数组.
I'm new with java and objectMapper. I'm trying to parse json field that is possible that a key have two types, it could be a string or array.
示例:
{
"addresses": [],
"full_name": [
"test name_1",
"test name_2"
],
}
或
{
{
"addresses": [],
"full_name": "test name_3",
}
}
类示例:
@JsonIgnoreProperties(ignoreUnknown = true)
@Data -> lombok.Data
public class Document {
private List<String> addresses;
@JsonProperty("full_name")
private String fullName;
}
我使用 objectMapper 反序列化 json,当 'full_name' 字段有一个字符串时可以正常工作,但是当到达数组时,反序列化失败.
I used objectMapper to deserialize json, works correctly when the 'full_name' field has a string but when arrive an array fail deserialization.
这个想法是,当一个字符串到达时,将值放入属性中,但当到达数组时,将数组元素连接为字符串 (String.join(",", value))
The idea is that when arrive a string put value in attribute but when arrive array, concatenate de array elements as string (String.join(",", value))
可以在类方法中应用自定义反序列化吗?例如 setFullName() (使用 lombok.Data)
It's possible to apply custom deserialization in a class method? For example setFullName() (use lombok.Data)
我在本网站上看到了其他示例,但不起作用.
I saw others examples in this site, but not work.
谢谢大家
推荐答案
从 jackson 2.6 你可以使用 JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY
From jackson 2.6 you can use JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY
@JsonProperty("full_name")
@JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
private String[] fullName;
这篇关于如何用Jackson解析可能是字符串也可能是数组的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!