问题描述
我必须从对象列表中序列化 JSON.生成的 JSON 必须如下所示:
I have to serialize JSON from a list of Objects. The resulting JSON has to look like this:
{
"status": "success",
"models": [
{
"model": {
"id": 23,
"color": "red"
}
},
{
"model": {
"id": 24,
"color": "green"
}
}
]
}
当我简单地序列化它时,我缺少类型/键模型":
I am missing the type/key "model" when I simply serialize this:
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"
}
]
}
如何为每个对象添加模型"而不必编写带有模型"属性的愚蠢包装类?
How can I add "model" for each object without having to write a silly wrapper class with a property "model"?
我的课程是这样的:
public class Response {
private String status;
private List<Model> models;
// getters / setters
}
public class Model {
private Integer id;
private String color;
// getters / setters
}
推荐答案
没有内置的方法可以做到这一点.您必须编写自己的 JsonSerializer
.类似的东西
There's no built-in way to do this. You'll have to write your own JsonSerializer
. Something like
class ModelSerializer extends JsonSerializer<List<Model>> {
@Override
public void serialize(List<Model> value, JsonGenerator jgen,
SerializerProvider provider) throws IOException {
jgen.writeStartArray();
for (Model model : value) {
jgen.writeStartObject();
jgen.writeObjectField("model", model);
jgen.writeEndObject();
}
jgen.writeEndArray();
}
}
然后注释 models
字段以便它使用它
and then annotate the models
field so that it uses it
@JsonSerialize(using = ModelSerializer.class)
private List<Model> models;
这将序列化为
{
"status": "success",
"models": [
{
"model": {
"id": 1,
"color": "red"
}
},
{
"model": {
"id": 2,
"color": "green"
}
}
]
}
如果您同时对其进行序列化和反序列化,则还需要一个自定义的反序列化器.
If you're both serializing and deserializing this, you'll need a custom deserializer as well.
这篇关于具有对象类型的 Jackson JSON 列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!