Problem Deserializing array as string with Jackson 2
This is a similar problem to Deserialize ArrayList from String using Jackson
The incoming JSON (which I can't control) has an element 'thelist' which is an array. However, sometimes this comes in as an empty string instead of an array:
eg. instead of "thelist" : [ ]
it comes in as "thelist" : ""
I'm having trouble parsing both cases.
The 'sample.json' file which works fine:
{
"name" : "widget",
"thelist" :
[
{"height":"ht1","width":"wd1"},
{"height":"ht2","width":"wd2"}
]
}
The classes:
public class Product {
private String name;
private List<Things> thelist;
// with normal getters and setters not shown
}
public class Things {
String height;
String width;
// with normal getters and setters not shown
}
The code that works fine:
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Test2 {
public static void main(String[] args)
{
ObjectMapper mapper = new ObjectMapper();
Product product = mapper.readValue( new File("sample.json"), Product.class);
}
}
However, when the JSON has got an empty string instead of an array, ie. "thelist" : ""
I get this error:
com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [collection type; class java.util.ArrayList, contains [simple type, class com.test.Things]] from JSON String; no single-String constructor/factory method (through reference chain: com.test.Product["thelist"])
If I add this line (which works for Ryan in Deserialize ArrayList from String using Jackson and seemingly supported by the documentation),
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
it makes no difference.
Is there some other setting, or do I need to write a custom deserializer?
If the latter, is there a simple example of doing this with Jackson 2.0.4 ?
I'm new to Jackson (and first time poster, so be gentle). I have done lots of searching, but can't find a good working example.