9
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