java and json jackson property - different types at run-time

jackson, java, json

Solution

A simple hack would be to enable DeserializationFeature#ACCEPT_SINGLE_VALUE_AS_ARRAY and then use Daniel's answer. If the web service returns a string, Jackson will turn it into a single-element collection.

EDIT:

If you can't upgrade to Jackson 1.8 or higher to use this feature, you could do something like:

private Collection<String> value;

public Collection<String> getValue() {
    return value;
}

public void setValue(Object value) {
    if (value instanceof Collection) {
        this.value = (Collection<String>) value;
    } else {
        this.value = Arrays.asList((String) value);
    }
}

Problem

I am calling an external web-service to get an object as json. This object has a property "value" which is sometimes a String and sometimes an array of Strings. ``` public class MyClass { // ... other variables private String value; public String getValue() { return value; } @JsonProperty("value") public void setValue(String value) { this.value = value; } } ``` Currently, I get an error `org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.lang.String out of START_ARRAY token` complaining about this field. I was wondering if some one could give me a hint on what is the correct way of defining `value` in my class. This is a part of a sample json that I have to deal with: ``` { "id": 12016907001, "type": "Create", "value": "normal", "field_name": "priority" }, { "id": 12016907011, "type": "Create", "value": [ "sample", "another" ], "field_name": "tags" } ``` Thanks. -- EDIT I changed the type of the value to Object and it solved my problem. However, I am still wondering if there is a better way to handle this case.

Original source