java - 如何使用 Jackson 解析可能是字符串也可能是数组的 json 字段

标签 java json annotations jackson deserialization

我有一个 json 字段,当有一个值时它是字符串:

{ "theField":"oneValue" }

当有多个值时为数组:

{ "theField": [ "firstValue", "secondValue" ] }

然后我有一个使用 com.fasterxml.jackson.annotation.JsonCreator 的 java 类:

public class TheClass { 
    private final List<String> theField;

    @JsonCreator
    public TheClass(@JsonProperty("theField") List<String> theField) {
        this.theField = theField;
    }
}

问题在于,当传入字段为字符串时,代码不起作用。抛出的异常是:

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token

如果我将其更改为期望字符串,它会针对数组抛出类似的异常...

如果我有任何关于我应该使用什么来代替 @JsonCreator 或如何使其适用于这两种类型的字段的想法,我将不胜感激

提前致谢,
斯坦·基拉鲁

最佳答案

也许您应该尝试以下操作:

public class TheClass { 
    private final List<String> theField;

    @JsonCreator
    public TheClass(@JsonProperty("theField") Object theField) {
        if (theField instanceof ArrayList) {
            this.theField = theField;
        } else {
            this.theField = new ArrayList<String>();
            this.theField.add(theField);
        }
    }
}

关于java - 如何使用 Jackson 解析可能是字符串也可能是数组的 json 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36330226/

相关文章:

java - Hibernate 验证注解——验证至少一个字段不为空

java - Spring MVC HTTP 状态 400 -

java - Windows:使用 File.listRoots 显示映射的网络驱动器

javascript - 将 json 存储为变量以便在另一个函数中重用

parameters - 在 DYMOLA 中显示注释中的参数

java - 在运行时访问注解

java - Play Framework 应用程序在第 6 行不断抛出空指针

java - 格式化文本字段未正确格式化 double 据

php - 从 mysql 检索数据返回相同的 3 行

javascript - 嵌套选择框问题更改第一个