我必须从对象列表中序列化JSON.生成的JSON必须如下所示:
{
"status": "success",
"models": [
{
"model": {
"id": 23,
"color": "red"
}
},
{
"model": {
"id": 24,
"color": "green"
}
}
]
}
当我简单地序列化时,我错过了类型/键“模型”:
List<Model> list = new ArrayList<Model>(); // add some new Model(...)
Response r = new Response("success", list); // Response has field "models"
相反,我得到这个:
{
"status": "success",
"models": [
{
"id": 23,
"color": "red"
},
{
"id": 24,
"color": "green"
}
]
}
如何为每个对象添加“模型”而无需编写具有属性“模型”的愚蠢包装类?
我的课程看起来像这样:
public class Response {
private String status;
private List<Model> models;
// getters / setters
}
public class Model {
private Integer id;
private String color;
// getters / setters
}
解决方法:
没有内置的方法来做到这一点.你必须编写自己的JsonSerializer.就像是
class ModelSerializer extends JsonSerializer<List<Model>> {
@Override
public void serialize(List<Model> value, JsonGenerator jgen,
SerializerProvider provider) throws IOException,
JsonProcessingException {
jgen.writeStartArray();
for (Model model : value) {
jgen.writeStartObject();
jgen.writeObjectField("model", model);
jgen.writeEndObject();
}
jgen.writeEndArray();
}
}
然后注释模型字段,以便它使用它
@JsonSerialize(using = ModelSerializer.class)
private List<Model> models;
这将序列化为
{
"status": "success",
"models": [
{
"model": {
"id": 1,
"color": "red"
}
},
{
"model": {
"id": 2,
"color": "green"
}
}
]
}
如果您同时序列化和反序列化,那么您还需要一个自定义反序列化器.