【问题标题】:Jackson Inheritance杰克逊遗产
【发布时间】:2019-06-03 18:40:29
【问题描述】:

似乎无法弄清楚这一点。我不断收到各种错误,所以我将用我从 Jackson 那里得到的当前错误来写这个。

public class ResponseDetail {
    private Response response;
}

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME)
@JsonSubTypes({
    @JsonSubTypes.Type(value = ResponseTypeOne.class, name = "ResponseTypeOne"),
    @JsonSubTypes.Type(value = ResponseTypeTwo.class, name = "ResponseTypeTwo"),
    @JsonSubTypes.Type(value = ResponseTypeThree.class, name = "ResponseTypeThree")
})
@JsonIgnoreProperties(ignoreUnknown = true)
public abstract class Response {
}

在其他包中我有这三个:

public class ResponseTypeOne extends Response {
     private Integer status;
}
public class ResponseTypeTwo extends Response {
    private String message;
}
public class ResponseTypeThree extends Response {
     private String value;
}

错误:

Caused by: com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Missing type id when trying to resolve subtype of [simple type, class com.services.models.Response]: missing type id property '@type' (for POJO property 'response')

我已经尝试了这个@JsonTypeInfo 与各种includes 和各种property 以及Id.CLASS 的各种迭代,但没有运气。

【问题讨论】:

    标签: spring-boot jackson jackson-databind


    【解决方案1】:

    您需要声明应该如何识别类型。

    @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "@ttype")
    @JsonSubTypes({
        @JsonSubTypes.Type(value = ResponseTypeOne.class, name = "ResponseTypeOne"),
        @JsonSubTypes.Type(value = ResponseTypeTwo.class, name = "ResponseTypeTwo"),
        @JsonSubTypes.Type(value = ResponseTypeThree.class, name = "ResponseTypeThree")
    })
    
    @JsonIgnoreProperties(ignoreUnknown = true)
    public abstract class Response {
       @JsonProperty("@ttype")
       public abstract String getChildType();
    }
    
    

    在子类型中,如下所示:

       @JsonTypeName("ResponseTypeOne")
        public class ResponseTypeOne extends Response {
            @Override
            public String getChildType() {
                return "ResponseTypeOne";
            }
        }
    

    传入的 json 应该如下所示,以使 jackson 能够找到正确的子实现:

    {
      //some attributes of child Response
      "@ttype": "ResponseTypeOne"
    }
    

    【讨论】:

    • 您好,感谢您的回答!这给了我Missing type id when trying to resolve subtype of [simple type, class com.services.resolve.models.authentication. ResponseTypeOne]: missing type id property '@ttype'
    • @user11475606 正在序列化或反序列化中?
    • 反序列化进入Java的json(在stackoverflow上cmets的长度必须是15个字符)
    • @user11475606 您是否将@ttype 成员放入到服务器的json 对象中?你能显示json吗?
    • 我将不得不稍微配置应用程序以将 JSON 响应记录到控制台。在ResponseTypeOne 我有这个@JsonProperty("@ttype") @Override public String getChildType() { return "ResponseTypeOne"; }
    猜你喜欢
    • 2013-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-25
    • 2020-04-12
    • 1970-01-01
    相关资源
    最近更新 更多