Skip to content
Advertisement

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;
}

Advertisement

Answer

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;
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement