简体   繁体   中英

Jackson Deserialization By Inheritance

I have a class with the following structure

Class A { private String type; private T entity; }

And my JSON structure is like this

{"type":"Relation1","entity":"{..}"} --> entity should be Relation1.class
{"type":"Relation2","entity":"{..}"}  --> entity should be Relation2.class

How can I achieve the desired outcome using Jackson deserilizaton?

If you use inheritance in your model you can't obtain a clean json like showed because Jackson couldn't deserialize the json. If you want to use Jackson you have to configure the ObjectMapper:

ObjectMapper mapper = new ObjectMapper();
mapper.enableDefaultTyping();

And then you will obtain a Json that include the T class name that is needed for deserialization process.

Here you find a complete guide: Guide

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM