【问题标题】:How to parse a json field that may be a string and may be an array with Jackson如何解析可能是字符串并且可能是 Jackson 数组的 json 字段
【发布时间】:2016-03-31 10:04:14
【问题描述】:

当只有一个值时,我有一个字符串的 json 字段:

{ "theField":"oneValue" }

当有多个值时为数组:

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

然后我的 java 类使用了 com.fasterxml.jackson.annotation.JsonCreator:

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 或如何使其适用于这两种类型的字段,我将不胜感激

提前致谢,
斯坦基拉鲁

【问题讨论】:

  • 嗯,我想在一个值的情况下不可能用包含一个字符串的数组替换字符串,对吧?
  • 我无法修改传入的 JSON - 这是第三方的东西 :(
  • 你试过@JsonProperty("theField") Object吗?
  • 然后你可以做类似try { this.theField = (List&lt;String&gt;) theField } catch (CastException e) { this.theField = new ArrayList&lt;String&gt;(); this.theField.add(theField); }
  • 使您的theField 成为对象而不是特定类型,将起作用。我刚在这里试过。问题是您必须进行一些类型验证才能稍后使用该字段。

标签: java json annotations jackson deserialization


【解决方案1】:

也许您应该尝试以下方法:

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);
        }
    }
}

【讨论】:

    猜你喜欢
    • 2020-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多