繁体   English   中英

使用 Jackson 反序列化 Java 中的 JSON

[英]Deserializing JSON in Java using Jackson

我有以下 JSON 的示例片段,我正在尝试反序列化。

{
    "total": 2236,
    "issues": [{
        "id": "10142",
        "key": "ID-2",
        "fields": {
            "attachment": [{
                "id": "11132"
            }]
        }
    }]
}

我可以将数据反序列化到 id 和 key,但不能反序列化字段中的附件。 我的附件 class 总是 null

这是我的代码。

响应.java

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class Response {

    @JsonProperty
    private int total;

    @JsonProperty
    private List<Issue> issues; 
}

问题.java

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class Issue {

    @JsonProperty
    private int id;

    @JsonProperty
    private String key;

    @JsonProperty
    private Fields fields;
}

字段.java

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class Fields {

    @JsonProperty
    private Attachments attachment;
}

附件.java

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class Attachments {

    @JsonProperty
    private List<Attachment> attachment; 
}

附件.java

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class Attachment {

    @JsonProperty
    private String id;
}

在您的 JSON 中, attachment是一个数组,而不是 object。

您不需要Attachments class,只需以这种方式修改Fields

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class Fields {

    @JsonProperty
    private List<Attachment> attachment;
}

将 Java 类中的每个变量视为对应于 JSON 中的属性。 “附件”不在 JSON 文件中。 您应该能够删除它并更改Fields class 中的变量定义。

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class Fields {

    @JsonProperty
    private List<Attachment> attachment;
}

如果您不想更改 class 结构,则可以修改 JSON。 attachment中,您需要再次添加一个attachment JSON 如下所示。

{
   "total":2233,
   "issues":[
      {
         "id":"13598",
         "key":"ID-2368",
         "fields":{
            "attachment":{
               "**attachment**":[
                  {
                     "id":"11122"
                  }
               ]
            }
         }
      }
   ]
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM