从另一个属性内部序列化JSON属性

时间:2017-02-27 09:08:27

标签: java json

我有以下JSON响应

{
    "id": "35346",
    "key": "CV-11",
    "fields": {
    "comment": {
        "total": 2,
        "comments": [
            {
                "id": 1234
                "body": "test comment1"
            },
            {
                "id": 1235
                "body": "test comment2"
            }
        ]
    },
    ....
}

我需要填充一个对应的Issue类,它将包含来自“fields”的Comments对象列表。像这样:

public class Issue {

    @JsonProperty
    public String id;

    @JsonProperty
    public String key;

    @JsonProperty
    public Map<String, Object> fields;

    @JsonProperty
    private List<Comment> comment = new ArrayList<>();
}

有办法吗?当前fields属性填充了字段,但comment属性始终为空。如何告诉序列化程序从内部字段中获取该注释?

1 个答案:

答案 0 :(得分:0)

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"}]}}