gpt4 book ai didi

java - 当您提前不知道 JSON 标签名称时 Jackson 和反序列化?

转载 作者:行者123 更新时间:2023-11-30 02:07:09 25 4
gpt4 key购买 nike

我想使用 Jackson 将 Jira 中的 JSON 反序列化为一组 POJO。我已经拥有了大部分我想要的功能,现在我只需解码自定义字段值即可。

我的输入 JSON 如下所示:

{
"expand": "renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations",
"id": "104144",
"self": "https://jira.internal.net/rest/api/2/issue/104144",
"key": "PRJ-524",
"fields": {
"summary": "Redo unit tests to load from existing project",
"components": [],
"customfield_10240": {
"self": "https://jira.internal.net/rest/api/2/customFieldOption/10158",
"value": "Normal",
"id": "10158"
}
}

我可以轻松加载摘要和组件,因为我提前知道这些 JSON 元素的名称是什么,并且可以在我的 POJO 中定义它们:

@JsonIgnoreProperties({ "expand", "self", "id", })
public class JiraJson
{
private JiraFields fields;
private String key;

public JiraFields getFields()
{
return fields;
}

public String getKey()
{
return key;
}

public void setFields(JiraFields newFields)
{
fields = newFields;
}

public void setKey(String newKey)
{
key = newKey;
}
}

对于 JiraFields 也类似:

@JsonIgnoreProperties({ "issuetype", "priority", "status" })
public class JiraFields
{
private List<JiraComponent> components;
private String summary;

public List<JiraComponent> getComponents()
{
return components;
}

public String getSummary()
{
return summary;
}

public void setComponents(List<JiraComponent> newComponents)
{
components = newComponents;
}

public void setSummary(String newSummary)
{
summary = newSummary;
}
}

但是,字段 custom_10240 实际上会有所不同,具体取决于运行该系统的 Jira 系统,在一个系统上为 custom_10240,在另一个系统上为 custom_10345 code>,所以我无法将其硬编码到 POJO 中。使用另一个调用,可以在运行时、反序列化开始之前知道字段的名称是什么,但这在编译时是不可能的。

假设我想将 value 字段映射到 JiraFields 上名为 ImportanceString,如何做我去做那件事吗?或者也许更简单,如何将此 Importance 映射到 JiraCustomField 类?

最佳答案

您可以使用用@JsonAnySetter注释的方法接受所有未定义(且不被忽略)的属性。如果是 Json 对象(如问题中的自定义字段),Jackson 会传递一个包含所有对象属性的 Map (在嵌套的情况下,它甚至可能包含 Map 值)对象)。您现在可以在运行时提取您想要的任何属性:

@JsonIgnoreProperties({ "issuetype", "priority", "status" })
public class JiraFields
{
private List<JiraComponent> components;
private String summary;
private String importance;

// getter/setter omitted for brevity

@JsonAnySetter
public void setCustomField(String name, Object value) {
System.out.println(name); // will print "customfield_10240"
if (value instanceof Map) { // just to make sure we got a Json Object
Map<String, Object> customfieldMap = (Map<String, Object>)value;
if (customfieldMap.containsKey("value")) { // check if object contains "value" property
setImportance(customfieldMap.get("value").toString());
}
}
}
}

关于java - 当您提前不知道 JSON 标签名称时 Jackson 和反序列化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51051926/

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