gpt4 book ai didi

java - 使用现有同级属性值对属性进行 Jackson 多态反序列化

转载 作者:行者123 更新时间:2023-11-30 05:24:13 26 4
gpt4 key购买 nike

我有一个使用 JSON 的现有 Request/Response 协议(protocol),但我无法控制该协议(protocol)。

示例 1:响应 JSON 不需要任何多态反序列化

{
"name" : "simple_response"
"params" : {
"success" : true
}
}

示例 2:响应 JSON 需要对 params 属性进行多态反序列化

{
"name" : "settings_response",
"params" : {
"success" : true,
"settings" : "Some settings info"
}
}

我的类结构如下所示:

class Response { // Not abstract. Used if no specialized response properties needed
@JsonProperty("params")
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.EXTERNAL_PROPERTY,
property = "name")
@JsonSubTypes({
@JsonSubTypes.Type(value=GetSettingsResponseParams.class, name="settings_response")
})
Params params;
String name; // Need to use its value to determine type of params
}

class Params {
boolean success;
}

class GetSettingsResponseParams extends Params {
String settings;
}

当我尝试反序列化“示例 2”中的 JSON 时,我得到:

Unexpected token (END_OBJECT), expected VALUE_STRING: need JSON String that contains type id (for subtype of com.foo.Params)

我做错了什么以及如何解决它?

最佳答案

响应模型应如下所示:

class Response {

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY, property = "name", visible = true)
@JsonSubTypes({
@JsonSubTypes.Type(value = GetSettingsResponseParams.class, name = "settings_response"),
@JsonSubTypes.Type(value = Params.class, name = "simple_response")
})
private Params params;
private String name;

// getters, settets, toString, etc.
}

上述模型适用于两个呈现的 JSON 有效负载。

关于java - 使用现有同级属性值对属性进行 Jackson 多态反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59000068/

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