问题描述
我有这个 POJO :
I have this POJO :
public class JsonObj {
private String id;
private List<Location> location;
public String getId() {
return id;
}
public List<Location> getLocation() {
return location;
}
@JsonSetter("location")
public void setLocation(){
List<Location> list = new ArrayList<Location>();
if(location instanceof Location){
list.add((Location) location);
location = list;
}
}
}
来自 json 输入的位置"对象可以是位置的简单实例或位置数组.当它只是一个实例时,我收到此错误:
the "location" object from the json input can be either a simple instance of Location or an Array of Location. When it is just one instance, I get this error :
Could not read JSON: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
我尝试实现自定义设置器,但没有奏效.如何根据 json 输入映射位置或列表?
I've tried to implement a custom setter but it didn't work. How could I do to map either a Location or a List depending on the json input?
推荐答案
更新:Mher Sarkissian's soulution 作品很好,它也可以按照此处的建议与注释一起使用,如下所示:
Update: Mher Sarkissian's soulution works fine, it can also be used with annotations as suggested here, like so:.
@JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
private List<Item> item;
我对这个最烦人的问题深表同情,我遇到了同样的问题,并在此处找到了解决方案:https://stackoverflow.com/a/22956168/1020871
稍加修改,我想出了这个,首先是泛型类:
With a little modification I come up with this, first the generic class:
public abstract class OptionalArrayDeserializer<T> extends JsonDeserializer<List<T>> {
private final Class<T> clazz;
public OptionalArrayDeserializer(Class<T> clazz) {
this.clazz = clazz;
}
@Override
public List<T> deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException {
ObjectCodec oc = jp.getCodec();
JsonNode node = oc.readTree(jp);
ArrayList<T> list = new ArrayList<>();
if (node.isArray()) {
for (JsonNode elementNode : node) {
list.add(oc.treeToValue(elementNode, clazz));
}
} else {
list.add(oc.treeToValue(node, clazz));
}
return list;
}
}
然后是属性和实际的反序列化器类(Java 泛型并不总是很漂亮):
And then the property and the actual deserializer class (Java generics is not always pretty):
@JsonDeserialize(using = ItemListDeserializer.class)
private List<Item> item;
public static class ItemListDeserializer extends OptionalArrayDeserializer<Item> {
protected ItemListDeserializer() {
super(Item.class);
}
}
这篇关于Jackson 映射对象或对象列表取决于 json 输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!