仅当存在某些字段时才使用自定义JSON反序列化(使用Jackson) [英] Custom JSON deserialization only if certain field is present (using Jackson)
问题描述
反序列化MyEntity
(这是一个接口)时,我要么拥有
When deserializing MyEntity
(which is an interface) I either have
-
以下输入:
the following input:
{ "id": 123 }
在这种情况下,我想将其反序列化为
in which case I would like to deserialize it into a
new MyEntityRef(123)
或者我输入以下内容:
or I have the following input:
{
"id": 123,
"message": "Hello world",
"otherEntity": {
"field": "value",
...
}
}
在这种情况下,我想将其反序列化为
in which case I would like to deserialize it as
new MyEntityImpl(123, "Hello world", otherEntity);
其中otherEntity
被反序列化的方式与在MyEntity
上下文之外找到它的方式相同.
where otherEntity
is deserialized the same way as if it was found outside the context of MyEntity
.
我已经找到了如何通过SimpleModule
注册自己的自定义反序列化器,但是我不知道如何
I've figured out how to register my own custom deserializer through a SimpleModule
but I don't know how to
- 根据某些字段(例如上面的
message
)的存在来选择自定义解串器. - 某些字段(例如上面的
otherEntity
)在默认"序列化程序上的回退.
- Choose a custom deserializer based on the presense of some field (such as
message
above). - Fallback on the "default" serializer for certain fields (such as
otherEntity
above).
推荐答案
通过如下配置我的ObjectMapper最终解决了该问题:
Finally solved it by configuring my ObjectMapper as follows:
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;
这篇关于仅当存在某些字段时才使用自定义JSON反序列化(使用Jackson)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!