如何使用Jackson解析可能是字符串并且可能是数组的json字段 [英] How to parse a json field that may be a string and may be an array with Jackson
问题描述
当有一个值时,我有一个字符串的json字段:
I have a json field that is string when there's one value:
{ "theField":"oneValue" }
或具有多个值的数组:
{ "theField": [ "firstValue", "secondValue" ] }
然后我有了使用com.fasterxml.jackson.annotation.JsonCreator的java类:
And then I have my java class that uses com.fasterxml.jackson.annotation.JsonCreator:
public class TheClass {
private final List<String> theField;
@JsonCreator
public TheClass(@JsonProperty("theField") List<String> theField) {
this.theField = theField;
}
}
问题在于,当输入字段为字符串时,代码不起作用.抛出的异常是:
The problem is that the code does not work when the incoming field is string. The exception thrown is:
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token
如果我将其更改为期望字符串,则会对数组抛出类似的异常...
And if I change it to expect string it throws the similar exception against an array...
对于使用什么代替@JsonCreator或如何使其适用于两种类型的字段的任何想法,我将不胜感激
I'd appreciate any ideas on what should I use instead of @JsonCreator or how to make it work with both types of field
在此先感谢,
斯坦·基拉鲁(Stan Kilaru)
Thanks in advance,
Stan Kilaru
推荐答案
也许您应该尝试以下操作:
Maybe you should try the following:
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);
}
}
}
这篇关于如何使用Jackson解析可能是字符串并且可能是数组的json字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!