I get JSON from a web service and can not influence the JSON format. The JSON code below is just an example to illustrate the problem. The field cars
can either be an object containing Car
objects or it can be an empty string. If I could change the web service, I'd change the empty String to be an empty object like "cars" : {}
instead of "cars" : ""
.
When trying to map JSON to this Java object:
public class Person {
public int id;
public String name;
public Map<String, Car> cars;
}
This works:
{
"id" : "1234",
"name" : "John Doe",
"cars" : {
"Tesla Model S" : {
"color" : "silver",
"buying_date" : "2012-06-01"
},
"Toyota Yaris" : {
"color" : "blue",
"buying_date" : "2005-01-01"
}
}
}
And this fails:
{
"id" : "1",
"name" : "The Dude",
"cars" : ""
}
What would be the best way to handle this case in Jackson? If there's the empty string, I'd like to get null
for the field cars
. I tried using ACCEPT_EMPTY_STRING_AS_NULL_OBJECT
, but it didn't help.
The "cars" element value is not a list (aka array). It's a JSON object, which can also be considered a map-type collection, but it is not a list.
So, to rephrase the issue, the goal is to deserialize JSON that is sometimes an object and sometimes an empty string into a Java
Map
.To solve this, I'm surprised
ACCEPT_EMPTY_STRING_AS_NULL_OBJECT
didn't work. I recommend logging an issue at http://jira.codehaus.org/browse/JACKSON.You could implement custom deserialization. Following is an example solution. If the target data structure has other
Map
references, then this solution would need to be accordingly changed.