jackson 实体转json 为NULL或者为空不参加序列化

package com.sarrs;

import ch.qos.logback.core.net.SyslogOutputStream;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
/**
 * Created by hubo7 on 2018/8/20.
 * test for : https://www.cnblogs.com/yangy608/p/3936848.html
 */
public class jacksonTest {
    private static ObjectMapper mapper = new ObjectMapper();
    public static void main(String[] args){
        Student stu = new Student("小明",112,"男");
        String stuStr = null;
        JSONObject stuJSONObject = null;
        try{
            //mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            stuStr = mapper.writeValueAsString(stu);
            stuJSONObject = JSON.parseObject(stuStr);
        }catch(Exception e){
            System.out.print(e.getMessage());
        }
        System.out.println(stuStr);
        System.out.println(stuJSONObject);
        System.out.println(stuJSONObject.toJSONString());
    }
}

@JsonInclude(JsonInclude.Include.NON_NULL)
class Student {
    private String name;
    private Integer id;
    private String sex;
    private String birthday;
    private String clazz;

    public Student() {
    }

    public Student(String name, Integer id, String sex) {
        this.name = name;
        this.id = id;
        this.sex = sex;
    }

    public String getName() {
        return name;
    }

    public Integer getId() {
        return id;
    }

    public String getSex() {
        return sex;
    }

    public String getBirthday() {
        return birthday;
    }

    public String getClazz() {
        return clazz;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    public void setClazz(String clazz) {
        this.clazz = clazz;
    }
}
原文地址:https://www.cnblogs.com/Allen-win/p/9510218.html