Abhijith Madhav Abhijith Madhav - 25 days ago 6
JSON Question

Jackson : How to serialize into an unnamed array

This is my POJO.

public class FolderPage {

private List<ApplicationIcon> applications;

public List<ApplicationIcon> getApplications() {
return applications;
}

public void setApplications(List<ApplicationIcon> applications) {
this.applications = applications;
}

@JsonCreator
public FolderPage(List<ApplicationIcon> applications) {
super();
this.applications = applications;
}
}


Currently it serializes as the below json
{
"applications": [{
"application": {
"id": "com.microsoft.onenote",
"name": "Micrsoft OneNote"
}
}, {
"application": {
"id": "com.microsoft.Office.word",
"name": "Microsoft word"
}
}]
}

However I want to serialize it into an unnamed json array like the below

[{
"application": {
"id": "com.microsoft.onenote",
"name": "Micrsoft OneNote"
}
}, {
"application": {
"id": "com.microsoft.Office.word",
"name": "Microsoft word"
}
}]


How can I achieve the same?

EDIT
POJO representing my application object

@JsonRootName("application")
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ApplicationIcon extends Icon {

private String id;
private String name;
}

Answer

Assuming ApplicationIcon has getId() and getName(). You can do it with custom Serializer:

public static class FolderPageSearialer extends JsonSerializer<FolderPage> {

        @Override
        public void serialize(FolderPage o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
            List<ApplicationIcon> applications = o.getApplications();
            jsonGenerator.writeStartArray(applications.size());
            for (ApplicationIcon application : applications) {
                jsonGenerator.writeStartObject();
                jsonGenerator.writeFieldName("application");
                jsonGenerator.writeStartObject();
                jsonGenerator.writeStringField("id", application.getId());
                jsonGenerator.writeStringField("name", application.getName());
                jsonGenerator.writeEndObject();
                jsonGenerator.writeEndObject();
            }
            jsonGenerator.writeEndArray();
        }
    }

And add @JsonSerialize on FolderPage class:

@JsonSerialize(using = FolderPage.FolderPageSearialer.class)
public class FolderPage