Custom JSON deserialization only if certain field is present (using Jackson)

对着背影说爱祢 提交于 2020-01-04 15:17:21

问题


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);
    

    where otherEntity is deserialized the same way as if it was found outside the context of MyEntity.

I've figured out how to register my own custom deserializer through a SimpleModule but I don't know how to

  1. Choose a custom deserializer based on the presense of some field (such as message above).
  2. Fallback on the "default" serializer for certain fields (such as otherEntity above).

回答1:


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;


来源:https://stackoverflow.com/questions/19463141/custom-json-deserialization-only-if-certain-field-is-present-using-jackson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!