I have DTO classes written in Java:
public class AnswersDto { private String uuid; private Set<AnswerDto> answers; } public class AnswerDto<T> { private String uuid; private AnswerType type; private T value; } class LocationAnswerDto extends AnswerDto<Location> { } class JobTitleAnswerDto extends AnswerDto<JobTitle> { } public enum AnswerType { LOCATION, JOB_TITLE, } class Location { String text; String placeId; } class JobTitle { String id; String name; }
My project has a Jackson library used to serialize and deserialize JSON.
How to configure AnswersDto (use special annotations) or AnswerDto (also annotations) classes to be able to properly deserialize a query using AnswersDto in your body, for example:
{ "uuid": "e82544ac-1cc7-4dbb-bd1d-bdbfe33dee73", "answers": [ { "uuid": "e82544ac-1cc7-4dbb-bd1d-bdbfe33dee73", "type": "LOCATION", "value": { "text": "Dublin", "placeId": "121" } }, { "uuid": "e82544ac-1cc7-4dbb-bd1d-bdbfe33dee73", "type": "JOB_TITLE", "value": { "id": "1", "name": "Developer" } } ] }
Unfortunately, Jackson maps the AnswerDto value of the object to the LinkedHashMap instead of the class object ( Location or JobTitle ). Should I write a custom JsonDeserializer<AnswerDto> or configuration using @JsonTypeInfo and @JsonSubTypes might be enough?
To properly deserialize a query with just one AnswerDto in the form
{ "uuid": "e82544ac-1cc7-4dbb-bd1d-bdbfe33dee73", "type": "LOCATION", "value": { "text": "Dublin", "placeId": "121" } }
I use:
AnswerDto<Location> answerDto = objectMapper.readValue(jsonRequest, new TypeReference<AnswerDto<Location>>() { });
without any other custom configuration.