【发布时间】:2015-03-08 16:29:06
【问题描述】:
我目前正在将一些代码从 Jackson 1.x 迁移到 Jackson 2.5 json 映射器,并且出现了一个 1.x 中不存在的问题。
这是设置(见下面的代码):
- 接口IPet
- 类Dog实现IPet
- IPet 使用 @JsonTypeInfo 和 @JsonSubTypes 注释
- 类 Human 具有使用 @JsonSerialize(using=CustomPetSerializer.class) 注释的 IPet 类型的属性
问题: 如果我序列化 Dog 的一个实例,它会按预期工作(Jackson 也将类型信息添加到 json 字符串中)。 但是,当我序列化 Human 类的实例时,会抛出异常:
com.fasterxml.jackson.databind.JsonMappingException:类型 id 处理 com.pet.Dog 类型未实现(通过引用链: com.Human["pet"])
未调用 CustomPetSerializer 类的 serialize(...) 方法(使用断点进行测试)。
代码:
IPet 实施:
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property="type")
@JsonSubTypes({
@JsonSubTypes.Type(value=Dog.class, name="dog")
//,@JsonSubTypes.Type(value=Cat.class, name="cat")
//more subtypes here...
})
public interface IPet
{
public Long getId();
public String getPetMakes();
}
狗实现:
public class Dog implements IPet
{
@Override
public String getPetMakes()
{
return "Wuff!";
}
@Override
public Long getId()
{
return 777L;
}
}
养狗的人:
public class Human
{
private IPet pet = new Dog();
@JsonSerialize(using=CustomPetSerializer.class)
public IPet getPet()
{
return pet;
}
}
CustomPetSerializer 实现:
public class CustomPetSerializer extends JsonSerializer<IPet>
{
@Override
public void serialize(IPet value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException
{
if(value != null && value.getId() != null)
{
Map<String,Object> style = new HashMap<String,Object>();
style.put("age", "7");
gen.writeObject(style);
}
}
}
JUnit 测试方法:
@Test
public void testPet() throws JsonProcessingException
{
ObjectMapper mapper = new ObjectMapper();
Human human = new Human();
//works as expcected
String json = mapper.writeValueAsString(human.getPet());
Assert.assertNotNull(json);
Assert.assertTrue(json.equals("{\"type\":\"dog\",\"id\":777,\"petMakes\":\"Wuff!\"}"));
//throws exception: Type id handling not implemented for type com.pet.Dog (through reference chain: com.Human["pet"])
json = mapper.writeValueAsString(human); //exception is thrown here
Assert.assertNotNull(json);
Assert.assertTrue(json.contains("\"age\":\"7\""));
}
【问题讨论】: