简体   繁体   English

使用 Jackson 反序列化 Java 中的 JSON

[英]Deserializing JSON in Java using Jackson

I have the following sample fragment of JSON I am trying to deserialize.我有以下 JSON 的示例片段,我正在尝试反序列化。

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

I can deserialize the data up to id and key, but cannot deserialize attachments that is in fields.我可以将数据反序列化到 id 和 key,但不能反序列化字段中的附件。 My attachment class is always null我的附件 class 总是 null

Here's my code.这是我的代码。

Response.java响应.java

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

    @JsonProperty
    private int total;

    @JsonProperty
    private List<Issue> issues; 
}

Issue.java问题.java

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

    @JsonProperty
    private int id;

    @JsonProperty
    private String key;

    @JsonProperty
    private Fields fields;
}

Fields.java字段.java

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

    @JsonProperty
    private Attachments attachment;
}

Attachments.java附件.java

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

    @JsonProperty
    private List<Attachment> attachment; 
}

Attachments.java附件.java

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

    @JsonProperty
    private String id;
}

In your JSON, attachment is an array, not an object.在您的 JSON 中, attachment是一个数组,而不是 object。

You don't need an Attachments class, just modify Fields this way:您不需要Attachments class,只需以这种方式修改Fields

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

    @JsonProperty
    private List<Attachment> attachment;
}

Think of each variable in your Java classes as corresponding to an attribute in the JSON.将 Java 类中的每个变量视为对应于 JSON 中的属性。 "Attachments" is not in the JSON file. “附件”不在 JSON 文件中。 You should be able to remove it and change the variable definition in the Fields class.您应该能够删除它并更改Fields class 中的变量定义。

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

    @JsonProperty
    private List<Attachment> attachment;
}

If you don't want to change class structure then, you can modify JSON.如果您不想更改 class 结构,则可以修改 JSON。 In attachment , you need to add again an attachment .attachment中,您需要再次添加一个attachment JSON would be like below. 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