根据JSON输入杰克逊映射对象或对象的列表 [英] Jackson mapping Object or list of Object depending on json input

查看:244
本文介绍了根据JSON输入杰克逊映射对象或对象的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的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?

推荐答案

我最深的这个最恼人的问题的同情,我刚刚同样的问题,在这里找到了解决办法:<一href=\"http://stackoverflow.com/a/22956168/1020871\">http://stackoverflow.com/a/22956168/1020871

My deepest sympathies for this most annoying problem, I had just the same problem and found the solution here: http://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泛型并不总是pretty):

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);
    }
}

这篇关于根据JSON输入杰克逊映射对象或对象的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆