首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从另一个属性内部序列化JSON属性

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

Stack Overflow用户
提问于 2017-02-27 17:08:27
回答 1查看 576关注 0票数 1

我有以下JSON响应

代码语言:javascript
复制
{
    "id": "35346",
    "key": "CV-11",
    "fields": {
    "comment": {
        "total": 2,
        "comments": [
            {
                "id": 1234
                "body": "test comment1"
            },
            {
                "id": 1235
                "body": "test comment2"
            }
        ]
    },
    ....
}

我需要填充一个对应的Issue类,它将具有来自“字段”的注释对象列表。如下所示:

代码语言:javascript
复制
public class Issue {

    @JsonProperty
    public String id;

    @JsonProperty
    public String key;

    @JsonProperty
    public Map<String, Object> fields;

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

有没有办法做到这一点?当前字段属性是用字段填充的,但注释属性始终为空。如何告诉序列化程序从字段内部获取注释?

EN

回答 1

Stack Overflow用户

发布于 2017-02-27 17:18:46

List<Comment>字段需要通过@JsonSerialize附加的自定义序列化程序

代码语言:javascript
复制
@JsonProperty
@JsonSerialize(using = CustomCommentSerialize.class)
private List<Comment> comment = new ArrayList<>();

然后您可以序列化到您的自定义格式...

代码语言:javascript
复制
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();
    }
}

示例

代码语言:javascript
复制
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));

输出

代码语言:javascript
复制
{"id":null,"key":null,"fields":null,"comment":{"total":2,"comments":[{"id":"123","body":"I'm a comment"},{"id":"456","body":"Another"}]}}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42481652

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档