我有以下JSON响应
{
"id": "35346",
"key": "CV-11",
"fields": {
"comment": {
"total": 2,
"comments": [
{
"id": 1234
"body": "test comment1"
},
{
"id": 1235
"body": "test comment2"
}
]
},
....
}我需要填充一个对应的Issue类,它将具有来自“字段”的注释对象列表。如下所示:
public class Issue {
@JsonProperty
public String id;
@JsonProperty
public String key;
@JsonProperty
public Map<String, Object> fields;
@JsonProperty
private List<Comment> comment = new ArrayList<>();
}有没有办法做到这一点?当前字段属性是用字段填充的,但注释属性始终为空。如何告诉序列化程序从字段内部获取注释?
发布于 2017-02-27 17:18:46
List<Comment>字段需要通过@JsonSerialize附加的自定义序列化程序
@JsonProperty
@JsonSerialize(using = CustomCommentSerialize.class)
private List<Comment> comment = new ArrayList<>();然后您可以序列化到您的自定义格式...
public class CustomCommentSerialize extends JsonSerializer<List<Comment>> {
@Override
public void serialize(List<Comment> comments, JsonGenerator gen, SerializerProvider arg2)
throws IOException, JsonProcessingException {
gen.writeStartObject();
gen.writeNumberField("total", comments.size());
gen.writeFieldName("comments");
gen.writeObject(comments);
gen.writeEndObject();
}
}示例
ObjectMapper mapper = new ObjectMapper();
Issue user = new Issue();
user.getComment().add(new Comment("123", "I'm a comment"));
user.getComment().add(new Comment("456", "Another"));
System.out.println(mapper.writeValueAsString(user));输出
{"id":null,"key":null,"fields":null,"comment":{"total":2,"comments":[{"id":"123","body":"I'm a comment"},{"id":"456","body":"Another"}]}}https://stackoverflow.com/questions/42481652
复制相似问题