Skip to content

Instantly share code, notes, and snippets.

@cjwcommuny
Created September 27, 2023 10:59
Show Gist options
  • Save cjwcommuny/ece745b503dc53d9492cefd6f5dd1a4c to your computer and use it in GitHub Desktop.
Save cjwcommuny/ece745b503dc53d9492cefd6f5dd1a4c to your computer and use it in GitHub Desktop.
Java Jackson Polymorphic Deserialization
package org.example;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Builder;
import lombok.SneakyThrows;
import lombok.Value;
import lombok.extern.jackson.Jacksonized;
import lombok.val;
public class Main {
@SneakyThrows
public static void main(String[] args) {
val fooJson = new ObjectMapper()
.writeValueAsString(Foo.builder().field("foo").build());
val barJson = new ObjectMapper()
.writeValueAsString(Bar.builder().flag(123).build());
val foo = new ObjectMapper()
.readValue(fooJson, Trait.class);
val bar = new ObjectMapper()
.readValue(barJson, Trait.class);
// class org.example.Foo
// Foo(field=foo)
// class org.example.Bar
// Bar(flag=123)
System.out.println(foo.getClass());
System.out.println(foo);
System.out.println(bar.getClass());
System.out.println(bar);
}
}
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.EXTERNAL_PROPERTY,
property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = Foo.class, name = "Foo"),
@JsonSubTypes.Type(value = Bar.class, name = "Bar")
})
interface Trait {
@JsonIgnore
String getMessage();
}
@Value
@Builder
@Jacksonized
@JsonTypeName("Foo")
class Foo implements Trait {
String field;
@Override
public String getMessage() {
return this.field;
}
}
@Value
@Builder
@Jacksonized
@JsonTypeName("Bar")
class Bar implements Trait {
int flag;
@Override
public String getMessage() {
return String.valueOf(this.flag);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment