jackson 序列化一个类怎么能生成多种JSON

发布于 2022-08-31 20:33:45 字数 1711 浏览 20 评论 0

javapublic class Board {

    private Integer boardId;
    private Integer userId;
    private String title;
    private String description;
    private String categoryId;
    private int seq;
    private long pinCount;
    private long followCount;
    private long likeCount;
    private long createdAt;
    private long updatedAt;
    private int deleting;
    private int isPrivate;
    private Object extra;

    private List<Pin> pins;
    private User user;

}

比如上面 Board

格式一: json :

json{
    "board_id": 18523725,
    "user_id": 12314505,
    "title": "室内软装之儿童房",
    "description": "",
    "category_id": "home",
    "seq": 18523725,
    "pin_count": 153,
    "follow_count": 81,
    "like_count": 7,
    "created_at": 1416270907,
    "updated_at": 1419990698,
    "deleting": 0,
    "is_private": 0,
    "extra": null,
    "pins": [],
    "user": {}
}

格式二: json :

json{
    "board_id": 18523725,
    "user_id": 12314505,
    "title": "室内软装之儿童房",
    "description": "",
    "category_id": "home",
    "seq": 18523725,
    "pin_count": 153,
    "follow_count": 81,
    "like_count": 7,
    "created_at": 1416270907,
    "updated_at": 1419990698,
    "deleting": 0,
    "is_private": 0
}

格式三: json :

json{
    "board_id": 18523725,
    "user_id": 12314505,
    "title": "室内软装之儿童房",
    "description": "",
    "category_id": "home"
}

等等。。。

图片描述

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

-残月青衣踏尘吟 2022-09-07 20:33:45

通过filter过滤字段可以达到这个目的

ObjectMapper mapper = new ObjectMapper();
// Exclude Null Fields
mapper.setSerializationInclusion(Inclusion.NON_NULL);
String[] ignorableFieldNames = { "pins", "user" };
FilterProvider filters = new SimpleFilterProvider()  
        .addFilter("filter Board",SimpleBeanPropertyFilter.serializeAllExcept(ignorableFieldNames));
ObjectWriter writer = mapper.writer(filters);
System.out.println(writer.writeValueAsString(new Board())); 

参考:http://stackoverflow.com/questions/13764280/how-do-i-exclude-fields-with-jackson-not-using-annotations

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文