[英]Serialize JSON property from inside another property
I have the following JSON response 我有以下JSON响应
{
"id": "35346",
"key": "CV-11",
"fields": {
"comment": {
"total": 2,
"comments": [
{
"id": 1234
"body": "test comment1"
},
{
"id": 1235
"body": "test comment2"
}
]
},
....
}
and I need to populate a correspondings Issue class which will have list of Comments objects from "fields". 我需要填充一个对应的Issue类,它将包含来自“fields”的Comments对象列表。 Something like this:
像这样的东西:
public class Issue {
@JsonProperty
public String id;
@JsonProperty
public String key;
@JsonProperty
public Map<String, Object> fields;
@JsonProperty
private List<Comment> comment = new ArrayList<>();
}
Is there a way to do that? 有没有办法做到这一点? Currently fields property is populated with fields, but comment property is always empty.
当前fields属性填充了字段,但comment属性始终为空。 How to tell serializer to take that Comments from inside fields?
如何告诉序列化程序从内部字段中获取该注释?
The List<Comment>
field needs a custom serializer attaching via @JsonSerialize
List<Comment>
字段需要通过@JsonSerialize
附加自定义序列化@JsonSerialize
@JsonProperty
@JsonSerialize(using = CustomCommentSerialize.class)
private List<Comment> comment = new ArrayList<>();
You can then serialize to your custom format... 然后,您可以序列化为自定义格式...
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();
}
}
Example 例
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));
Output 产量
{"id":null,"key":null,"fields":null,"comment":{"total":2,"comments":[{"id":"123","body":"I'm a comment"},{"id":"456","body":"Another"}]}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.