对于FasterXML的Jackon JSON开发人员来说,这是一个普遍的问题。当我遇到类似的POJO时,我遇到了它:
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
}
此类与以下JSON消息匹配...
{
"family" : "net.package.dogs.retrievers.GoldenRetriever",
"name" : "Goldie",
"color" : "YELLOW"
}
{
"family" : "net.package.dogs.retrievers.LabradorRetriever",
"name" : "Cookie",
"color" : "CHOCOLATE"
}
但是,我希望有一个不同的“种族”,如下所示。
{
"family" : "GOLDEN_RETRIEVER",
"name" : "Goldie",
"color" : "YELLOW"
}
{
"family" : "LABRADOR_RETRIEVER",
"name" : "Cookie",
"color" : "CHOCOLATE"
}
如何填写
JsonTypeInfo
和JsonSubTypes
来匹配此先前的JSON消息? 最佳答案
这是您可以完成此操作的一种方法:
更改@JsonTypeInfo
以使用JsonTypeInfo.Id.NAME
:
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, ...
添加
@JsonTypeName
进行名称解析:@JsonTypeName("LABRADOR_RETRIEVER")
public class LabradorRetriever extends Retriever {