0

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?

Sanchu Varkey
  • 49
  • 1
  • 5

1 Answers1

0

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

  • Will it help If I change ``private T entity;`` to ``private AbstractRelation entity;`` – Sanchu Varkey May 26 '20 at 21:53
  • No, I'm sorry. But if Relation1 and Relation2 has the same fields you can set a concrete superclass Relation and put it in the model. In this way your json will be clear and when you deserialize the json you will obtain a Relaction instance. then From the fields's values you can cast the instance to the correct RelationN class. – Simone Casamassa May 28 '20 at 08:28