Created
October 13, 2019 10:20
-
-
Save maglighter/940af07101abdacda4c9126d79581f8b to your computer and use it in GitHub Desktop.
Make jackson deserialize objects with the support of polymorphism
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.fasterxml.jackson.annotation.JsonTypeInfo; | |
import com.fasterxml.jackson.databind.ObjectMapper; | |
import lombok.AllArgsConstructor; | |
import lombok.Builder; | |
import lombok.Data; | |
import lombok.NoArgsConstructor; | |
@Data | |
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@type") | |
abstract class Parent { | |
private int id; | |
} | |
@Data | |
class ChildOne extends Parent {} | |
@Data | |
class ChildTwo extends Parent {} | |
@Data | |
@Builder | |
@NoArgsConstructor | |
@AllArgsConstructor | |
class JsonDto<T extends Parent> { | |
private T content; | |
} | |
class Scratch { | |
public static void main(String[] args) { | |
JsonDto dto = JsonDto.builder() | |
.content(new ChildTwo()) | |
.build(); | |
ObjectMapper objectMapper = new ObjectMapper(); | |
try { | |
String json = objectMapper.writeValueAsString(dto); | |
System.out.println(json); | |
JsonDto deserialized = objectMapper.readValue(json, JsonDto.class); | |
System.out.println("Deserialized Json Class: " + deserialized.getClass().getSimpleName()); | |
String deserializedJson = objectMapper.writeValueAsString(deserialized); | |
System.out.println(deserializedJson); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment