This is a popular problem for FasterXML's Jackon JSON developers. I faced it when I had with similiar POJOs:
package net.package.dogs.retrievers
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "family")
@JsonSubTypes(value = {
@JsonSubTypes.Type(value = LabradorRetriever.class),
@JsonSubTypes.Type(value = GoldenRetriever.class)
})
public abstract class Retriever {
private String name;
private Color color;
public Retriever() {}
public Retriever(String name, Color color) {
this.name = name;
this.color = color;
}
public String bark() {
return "You can't hear me but I'm barking";
}
}
package net.package.dogs.retrievers
public class LabradorRetriever extends Retriever {
public LabradorRetriever() {
super();
}
public LabradorRetriever(String name, Color color) {
super(name, color);
}
public String bark() {
return "Ruff! Ruff!";
}
public String fetchDucks() {
return "ufff...";
}
}
package net.package.dogs.retrievers
public class GoldenRetriever extends Retriever {
public GoldenRetriever() {
super();
}
public GoldenRetriever(String name, Color color) {
super(name, color);
}
public String bark() {
return "Wruuff! Wruff!";
}
}
public enum Color {
YELLOW,
CHOCOLATE,
BLACK
}
This classes match the following JSON messages...
{
"family" : "net.package.dogs.retrievers.GoldenRetriever",
"name" : "Goldie",
"color" : "YELLOW"
}
{
"family" : "net.package.dogs.retrievers.LabradorRetriever",
"name" : "Cookie",
"color" : "CHOCOLATE"
}
But instead I want to have a different different "race" as follows.
{
"family" : "GOLDEN_RETRIEVER",
"name" : "Goldie",
"color" : "YELLOW"
}
{
"family" : "LABRADOR_RETRIEVER",
"name" : "Cookie",
"color" : "CHOCOLATE"
}
How should I fill JsonTypeInfo
and JsonSubTypes
to match this previous JSON message?