使用Jackson来自JSON,其中每个类实现相同的接口

时间:2015-07-24 15:30:07

标签: java json serialization jackson deserialization

我试图使用Jackson反序列化一个相当复杂的JSON结构。

序列化工作正常:

Param界面:

public interface Param<T> {
}

Not.java:

public class Not implements Param<Param<?>> {

    private Param not;

    public Not(){

    }

    public Not(Param not) {
        this.not = not;
    }

    public Param getNot() {
        return not;
    }

}

And.java:

public class And implements Param<List<?>> {

    private List<Param> and;

    public List<Param> getAnd() {
        return and;
    }

    public List<Param> add(Param ... params){
        for (Param param : params){
            this.and.add(param);
        }
        return this.and;
    }

    public And() {
        this.and = new ArrayList<>();
    }

    public And(Param ... params){
        this.and = new ArrayList<>();
        for (Param param : params){
            this.and.add(param);
        }
    }

}

Company.java:

public class CompanyName implements Param<String> {

    private String companyName;

    public CompanyName(String value) {
        this.companyName = value;
    }

    public String getCompanyName() {
        return companyName;
    }
}

序列化:

ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(new And(new Or(new CompanyName("ABC"), new CompanyName("DEF")), new Not(new CompanyName("GHI")))));

打印:

{"and":[{"or":[{"companyName":"ABC"},{"companyName":"DEF"}]},{"not":{"companyName":"GHI"}}]}

现在反序列化,杰克逊如何知道如何映射和/或/ companyName /不回到他们的对象?

And and = mapper.readValue(json, And.class);
  

线程中的异常&#34; main&#34;   com.fasterxml.jackson.databind.JsonMappingException:无法构造   com.ahp.messaging.param.Param的实例,问题:抽象类型   要么需要映射到具体类型,要有自定义反序列化器,   或者在[来源:使用其他类型信息进行实例化   {&#34;和&#34;:[{&#34;或&#34;:[{&#34;的companyName&#34;:&#34; ABC&#34;},{&#34;的companyName&#34 ;:&#34; DEF&#34;}]},{&#34;不&#34; {&#34;的companyName&#34;:&#34; GHI&#34;}}]};   line:1,column:9](通过参考链:   com.ahp.messaging.param.And [&#34;和&#34;] - &GT; java.util.ArrayList中[0])

为了摆脱异常,我修改了Param接口,如下所示:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "T", visible = false)
@JsonSubTypes({
    @JsonSubTypes.Type(value = Not.class, name = "not"),
    @JsonSubTypes.Type(value = And.class, name = "and"),
    @JsonSubTypes.Type(value = Or.class, name = "or"),
    @JsonSubTypes.Type(value = CompanyName.class, name = "companyName")

})
public interface Param<T> {

}

现在它序列化为:

{"T":"and","and":[{"T":"or","or":[{"T":"companyName","companyName":"ABC"},{"T":"companyName","companyName":"DEF"}]},{"T":"not","not":{"T":"companyName","companyName":"GHI"}}]}

完全反序列化,但有关于所有内容的类型信息,有没有办法摆脱类型信息,只有它真正需要它?

1 个答案:

答案 0 :(得分:0)

简短回答,需要输入类型信息。

使用XML,您可以获得包含每个元素的类型信息,使用JSON,您可以牺牲较小表示的类型信息,但在这种情况下,删除类型信息意味着无法推断它应该映射到哪个类到。