使用JsonSubTypes和JsonTypeInfo快速获得Jackson Jackson的JSON多态性

时间:2015-04-17 19:33:35

标签: java json polymorphism jackson fasterxml

对于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"
}

如何填写JsonTypeInfoJsonSubTypes以匹配之前的JSON消息?

1 个答案:

答案 0 :(得分:1)

以下是一种可以实现此目的的方法:

  1. @JsonTypeInfo更改为使用JsonTypeInfo.Id.NAME

    @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, ...
    
  2. 添加@JsonTypeName以进行名称解析:

    @JsonTypeName("LABRADOR_RETRIEVER")
    public class LabradorRetriever extends Retriever {