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



 java


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

等等。。。

图片描述

java json jackson

琐琐碎碎2 10 years, 4 months ago

通过 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

无所不在的大海 answered 10 years, 4 months ago

Your Answer