如何使用杰克逊解析可能是字符串并且可能是数组的字段 [英] How to parse field that may be a string and may be an array with Jackson

查看:60
本文介绍了如何使用杰克逊解析可能是字符串并且可能是数组的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是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.

想法是,当到达属性中的字符串放置值但到达数组时,将de数组元素连接为字符串(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中,您可以使用

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;

这篇关于如何使用杰克逊解析可能是字符串并且可能是数组的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆