Fastjson输出空值

1 Fastjson默认的空值处理

在Fastjson中,默认情况下是不输出空值(NULL)的。无论Map中的NULL和对象属性中的NULL,序列化的时候都会被忽略不输出,这样会减少产生文本的大小。但如果需要输出空值怎么做呢?

2 Fastjson空值处理的方法

如果你需要输出空值,需要设置SerializerFeature常量值来控制NULL值的输出,下面列出不同情况的空值处理方法:

SerializerFeature常量 说明
WriteMapNullValue 是否输出值为NULL的Map字段,默认为false
WriteNullStringAsEmpty 字符类型字段如果为NULL,输出为空字符串,而非NULL
WriteNullListAsEmpty List字段如果为NULL,输出为[],而非NULL
WriteNullNumberAsZero 数值字段如果为NULL,输出为0,而非NULL
WriteNullBooleanAsFalse Boolean字段如果为NULL,输出为false,而非NULL

3 忽略空值的示例

3.1 设计Student实体类

package com.yiidian.domain;

/**
 * 一点教程网 - http://www.yiidian.com
 */
public class Student {
    private String studentName;
    private Integer studentAge;

    public Student() {
    }

    public Student(String studentName, Integer studentAge) {
        this.studentName = studentName;
        this.studentAge = studentAge;
    }

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public Integer getStudentAge() {
        return studentAge;
    }

    public void setStudentAge(Integer studentAge) {
        this.studentAge = studentAge;
    }

    @Override
    public String toString() {
        return "Student{" +
                "studentName='" + studentName + '\'' +
                ", studentAge=" + studentAge +
                '}';
    }
}

3.2 编写测试类

MainApp:

package com.yiidian.fastjson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.yiidian.domain.Student;
import com.yiidian.domain.Teacher;

/**
 * 一点教程网 - http://www.yiidian.com
 */
public class MainApp {

    public static void main(String args[]){

        Student student = new Student();
        student.setStudentName("eric");
        //注意:studentAge为NULL

        //默认情况下NULL值被忽略不输出
        String jsonstring = JSON.toJSONString(student);
        System.out.println(jsonstring);

    }

}

3.3 运行结果

4 不忽略空值的示例

4.1 编写测试类

MainApp:

package com.yiidian.fastjson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.yiidian.domain.Student;

/**
 * 一点教程网 - http://www.yiidian.com
 */
public class MainApp {

    public static void main(String args[]){

        Student student = new Student();
        student.setStudentName("eric");
        //注意:studentAge为NULL

        //改为不忽略NULL值
        String jsonstring = JSON.toJSONString(student,SerializerFeature.WriteMapNullValue);
        System.out.println(jsonstring);

    }

}

4.2 运行结果