问题
I have a json field that is string when there's one value:
{ "theField":"oneValue" }
or array when there are multiple values:
{ "theField": [ "firstValue", "secondValue" ] }
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...
I'd appreciate any ideas on what should I use instead of @JsonCreator or how to make it work with both types of field
Thanks in advance,
Stan Kilaru
回答1:
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);
}
}
}
来源:https://stackoverflow.com/questions/36330226/how-to-parse-a-json-field-that-may-be-a-string-and-may-be-an-array-with-jackson