1 回答
TA贡献1921条经验 获得超9个赞
在这个答案的帮助下,我找到了解决方案:自定义反序列化器需要基于默认反序列化器,它正确实现了反向引用机制。
这比仅仅从正确的基类继承要复杂一些。相反,您需要通过自定义获取(完全配置的)默认反序列化器实例BeanDeserializerModifier
,然后将此实例传递给您的子类DelegatingDeserializer
:
public ObjectMapper getMapperWithCustomDeserializer() {
ObjectMapper objectMapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.setDeserializerModifier(new BeanDeserializerModifier() {
@Override
public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config,
BeanDescription beanDesc, JsonDeserializer<?> defaultDeserializer) {
if (beanDesc.getBeanClass() == User.class) {
return new UserDeserializer(defaultDeserializer);
} else {
return defaultDeserializer;
}
}
});
objectMapper.registerModule(module);
return objectMapper;
}
然后自定义反序列化器需要如下所示:
public class UserDeserializer extends DelegatingDeserializer {
public UserDeserializer(JsonDeserializer<?> delegate) {
super(delegate);
}
@Override
protected JsonDeserializer<?> newDelegatingInstance(JsonDeserializer<?> newDelegate) {
return new UserDeserializer(newDelegate);
}
@Override
public User deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException {
String key = p.getCurrentName();
User result = (User) super.deserialize(p, ctxt);
result.userId = key;
return result;
}
}
最后,您需要删除@JsonDeserialize注释。然后,自定义反序列化器和@JsonBackReference应该工作。
添加回答
举报