杰克逊:如何序列化为一个未命名的数组

时间:2016-11-11 07:08:39

标签: java json serialization jackson

这是我的POJO。

    $ cat ad.sh.bak2 |perl -ne '/\|$/ && print'
    $ cat ad.sh.bak2 |perl -ne '/\|$ */ && print'
    $

目前它序列化为下面的json     {         “申请”:[{             “申请”:{                 “id”:“com.microsoft.onenote”,                 “名字”:“Micrsoft OneNote”             }         },{             “申请”:{                 “id”:“com.microsoft.Office.word”,                 “名字”:“微软的话”             }         }]     }

但是我想把它序列化为一个未命名的json数组,如下面的

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

我怎样才能达到同样的目标?

修改 POJO代表我的应用程序对象

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

1 个答案:

答案 0 :(得分:1)

假设ApplicationIcongetId()getName()。您可以使用自定义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();
        }
    }

在FolderPage类上添加@JsonSerialize:

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