gpt4 book ai didi

spring-boot - jackson 遗产

转载 作者:行者123 更新时间:2023-12-05 03:00:53 25 4
gpt4 key购买 nike

似乎无法弄清楚这一点。我一直收到各种错误,所以我只用我从 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 没有运气。

最佳答案

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

@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"
}

关于spring-boot - jackson 遗产,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56432866/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com