我有一个 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/