Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson mapping Object or list of Object depending on json input

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

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

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?

like image 512
TrtG Avatar asked Jan 11 '14 14:01

TrtG


People also ask

How does Jackson read JSON files?

databind. ObjectMapper ) is the simplest way to parse JSON with Jackson. The Jackson ObjectMapper can parse JSON from a string, stream or file, and create a Java object or object graph representing the parsed JSON. Parsing JSON into Java objects is also referred to as to deserialize Java objects from JSON.

How do I convert a JSON list to Jackson?

We can convert a List to JSON array using the writeValueAsString() method of ObjectMapper class and this method can be used to serialize any Java value as a String.


1 Answers

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;

My deepest sympathies for this most annoying problem, I had just the same problem and found the solution here: 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;
    }
}

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);
    }
}
like image 134
Love Avatar answered Oct 03 '22 02:10

Love