【发布时间】: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<String>) theField } catch (CastException e) { this.theField = new ArrayList<String>(); this.theField.add(theField); } -
使您的
theField成为对象而不是特定类型,将起作用。我刚在这里试过。问题是您必须进行一些类型验证才能稍后使用该字段。
标签: java json annotations jackson deserialization