编程语言
首页 > 编程语言> > java – Jackson根据json输入映射Object或Object列表

java – Jackson根据json输入映射Object或Object列表

作者:互联网

我有这个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输入中的“location”对象可以是Location的简单实例,也可以是Location的Array.当它只是一个实例时,我收到此错误:

Could not read JSON: Can not deserialize instance of java.util.ArrayList out of   START_OBJECT token

我试图实现自定义setter但它不起作用.我怎么能根据json输入映射位置或列表?

解决方法:

更新:Mher Sarkissian’s soulution工作正常,它也可以使用建议here注释,如下所示:

@JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
private List<Item> item;

我对这个最烦人的问题表示最深切的同情,我遇到了同样的问题并在此找到了解决方案:https://stackoverflow.com/a/22956168/1020871

通过一点修改,我想出了这个,首先是泛型类:

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泛型并不总是很漂亮):

@JsonDeserialize(using = ItemListDeserializer.class)
private List<Item> item;

public static class ItemListDeserializer extends OptionalArrayDeserializer<Item> {
    protected ItemListDeserializer() {
        super(Item.class);
    }
}

标签:android,java,json,jackson,rest-client
来源: https://codeday.me/bug/20190930/1836247.html