现场汽车可以包含汽车对象列表
...
这有效:
{
"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"
}
}
}
“cars”元素值不是列表(也称为数组)。它是一个JSON对象,也可以认为是一个map类型的集合,但它不是一个列表。
因此,重新表述这个问题,目标是将有时是对象有时是空字符串的 JSON 反序列化为 JavaMap
.
为了解决这个问题,我很惊讶ACCEPT_EMPTY_STRING_AS_NULL_OBJECT http://jackson.codehaus.org/1.8.2/javadoc/org/codehaus/jackson/map/DeserializationConfig.Feature.html#ACCEPT_EMPTY_STRING_AS_NULL_OBJECT没用。我建议将问题记录在http://jira.codehaus.org/browse/JACKSON http://jira.codehaus.org/browse/JACKSON.
你可以实施自定义反序列化 http://wiki.fasterxml.com/JacksonHowToCustomDeserializers。以下是一个示例解决方案。如果目标数据结构有其他Map
参考文献,那么这个解决方案就需要做相应的改变。
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.ObjectCodec;
import org.codehaus.jackson.Version;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.module.SimpleModule;
import org.codehaus.jackson.type.TypeReference;
public class Foo
{
public static void main(String[] args) throws Exception
{
SimpleModule module = new SimpleModule("CarsDeserializer", Version.unknownVersion());
module.addDeserializer(Map.class, new CarsDeserializer());
ObjectMapper mapper = new ObjectMapper().withModule(module);
Person person1 = mapper.readValue(new File("input1.json"), Person.class);
System.out.println(mapper.writeValueAsString(person1));
// {"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"}}}
Person person2 = mapper.readValue(new File("input2.json"), Person.class);
System.out.println(mapper.writeValueAsString(person2));
// {"id":1,"name":"The Dude","cars":{}}
}
}
class Person
{
public int id;
public String name;
public Map<String, Car> cars;
}
class Car
{
public String color;
public String buying_date;
}
class CarsDeserializer extends JsonDeserializer<Map<String, Car>>
{
@Override
public Map<String, Car> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException,
JsonProcessingException
{
ObjectCodec codec = jp.getCodec();
JsonNode node = codec.readTree(jp);
if (!"".equals(node.getTextValue()))
{
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(node, new TypeReference<Map<String, Car>>() {});
}
return new HashMap<String, Car>(); // or return null, if preferred
}
}