反序列化MyEntity
(这是一个接口)时,我要么
以下输入:
{ "id": 123 }
在这种情况下,我想将其反序列化为
new MyEntityRef(123)
或者我有以下输入:
{
"id": 123,
"message": "Hello world",
"otherEntity": {
"field": "value",
...
}
}
在这种情况下,我想反序列化为
new MyEntityImpl(123, "Hello world", otherEntity);
在哪里otherEntity
反序列化的方式与在的上下文之外找到它的方式相同MyEntity
。
我已经想出了如何通过来注册自己的自定义反序列化器,SimpleModule
但是我不知道如何
message
如上),选择一个自定义解串器。otherEntity
上述字段)的“默认”序列化程序进行回退。最后通过配置我的ObjectMapper来解决它,如下所示:
ObjectMapper mapper = new ObjectMapper();
SimpleModule idAsRefModule = new SimpleModule("ID-to-ref",
new Version(1, 0, 0, null));
idAsRefModule.addDeserializer(TestEntity.class,
new JsonDeserializer<TestEntity>() {
@Override
public TestEntity deserialize(JsonParser jp, DeserializationContext dc)
throws IOException, JsonProcessingException {
ObjectCodec codec = jp.getCodec();
JsonNode node = codec.readTree(jp);
boolean isFullImpl = node.has("message");
Class<? extends TestEntity> cls = isFullImpl ? TestEntityImpl.class
: TestEntityRef.class;
return codec.treeToValue(node, cls);
}
});
mapper.registerModule(idAsRefModule);
return mapper;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句