user2254180
user2254180

Reputation: 856

Deserializing JSON in Java using Jackson

I have the following sample fragment of JSON I am trying to deserialize.

{
    "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. My attachment class is always null

Here's my code.

Response.java

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

    @JsonProperty
    private int total;

    @JsonProperty
    private List<Issue> issues; 
}

Issue.java

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

    @JsonProperty
    private int id;

    @JsonProperty
    private String key;

    @JsonProperty
    private Fields fields;
}

Fields.java

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

    @JsonProperty
    private Attachments attachment;
}

Attachments.java

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

    @JsonProperty
    private List<Attachment> attachment; 
}

Attachments.java

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

    @JsonProperty
    private String id;
}

Upvotes: 0

Views: 102

Answers (3)

Shivkumar Kawtikwar
Shivkumar Kawtikwar

Reputation: 210

If you don't want to change class structure then, you can modify JSON. In attachment, you need to add again an attachment. JSON would be like below.

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

Upvotes: 0

Alex Voss
Alex Voss

Reputation: 176

Think of each variable in your Java classes as corresponding to an attribute in the JSON. "Attachments" is not in the JSON file. You should be able to remove it and change the variable definition in the Fields class.

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

    @JsonProperty
    private List<Attachment> attachment;
}

Upvotes: 1

Arnaud
Arnaud

Reputation: 17534

In your JSON, attachment is an array, not an object.

You don't need an Attachments class, just modify Fields this way:

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

    @JsonProperty
    private List<Attachment> attachment;
}

Upvotes: 2

Related Questions