gpt4 book ai didi

java - 使用 @JsonSubTypes 进行反序列化以获得无值 - 缺少属性错误

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:59:14 25 4
gpt4 key购买 nike

我这样反序列化 jsons:

{
"type":"a",
"payload" : {...}
}

有效负载类型取决于类型。我的类(class):

public class Sth<T extends Payload> {

@JsonProperty("type")
private String type;
@Valid
private T payload;

@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.EXTERNAL_PROPERTY,
property = "type",
visible = true,
defaultImpl = NoClass.class)
@JsonSubTypes({
@JsonSubTypes.Type(value = APayload.class, name = "a"),
@JsonSubTypes.Type(value = BPayload.class, name = "b"),
@JsonSubTypes.Type(value = CPayload.class, name = "c")})
public void setPayload(T payload) {
this.payload = payload;
}

public void setType(String type) {
this.type = type;
}

}

我还输入了没有负载的“d”。如果我尝试反序列化:

{
"type":"d",
"payload" : null
}

它可以工作,但它不能在没有有效负载的情况下工作:

{
"type":"d",
}

如何让它与上一个例子一起工作?

我得到的错误堆栈跟踪:

[error] Caused by: com.fasterxml.jackson.databind.JsonMappingException: Missing property 'payload' for external type id 'type
[error] at [Source: N/A; line: -1, column: -1]
[error] at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:164)
[error] at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:700)
[error] at com.fasterxml.jackson.databind.deser.impl.ExternalTypeHandler.complete(ExternalTypeHandler.java:160)
[error] at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeWithExternalTypeId(BeanDeserializer.java:690)
[error] at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeWithExternalTypeId(BeanDeserializer.java:639)
[error] at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:266)
[error] at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:124)
[error] at com.fasterxml.jackson.databind.ObjectMapper._readValue(ObjectMapper.java:2965)
[error] at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:1587)
[error] at com.fasterxml.jackson.databind.ObjectMapper.treeToValue(ObjectMapper.java:1931)
[error] at play.libs.Json.fromJson(Json.java:47)

最佳答案

有明确的反序列化功能:

new ObjectMapper().configure(
DeserializationFeature.FAIL_ON_MISSING_EXTERNAL_TYPE_ID_PROPERTY,
false);

关于java - 使用 @JsonSubTypes 进行反序列化以获得无值 - 缺少属性错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28089484/

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