fastjson 的 JSONObject.toJSONString() 默认忽略值为 null 的属性

现象

使用 fastjson 的 JSONObject.toJSONString() 将实体对象转成 JSON 字符串时,部分属性莫名其妙地消失了,影响后续的使用。

示例代码

    @Test
    public void testNoNull() {
        Person person = new Person();
        person.setName("jia");
        person.setAge(6);
        person.setArea("上海长宁");
        System.out.println(JSONObject.toJSONString(person));
    }

    public class Person {
        private String name;
        private int age;
        private String area;
        private String like;

        public String getName() {
            return name;
        }

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

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        public String getArea() {
            return area;
        }

        public void setArea(String area) {
            this.area = area;
        }

        public String getLike() {
            return like;
        }

        public void setLike(String like) {
            this.like = like;
        }
    }

输出结果

{"age":6,"area":"上海长宁","name":"jia"}

由上可知,输出结果中不包含 “like” 属性。

原因

fastjson 的 JSONObject.toJSONString() 默认忽略值为 null 的属性。

解决方案

设置 fastjson 的 SerializerFeature 的值为 WriteMapNullValue,输出值为 null 的属性。

示例代码

    @Test
    public void testWithNull() {
        Person person = new Person();
        person.setName("jia");
        person.setAge(6);
        person.setArea("上海长宁");
        System.out.println(JSONObject.toJSONString(person, SerializerFeature.WriteMapNullValue));
    }

输出结果

{"age":6,"area":"上海长宁","like":null,"name":"jia"}

拓展

JSON 的 public static String toJSONString(Object object, SerializerFeature… features) 方法中可以接收多个 SerializerFeature 类型的参数;而 SerializerFeature 是枚举类型,定义的枚举对象如下:

public enum SerializerFeature {
    QuoteFieldNames,
    UseSingleQuotes,
    WriteMapNullValue,
    WriteEnumUsingToString,
    WriteEnumUsingName,
    UseISO8601DateFormat,
    WriteNullListAsEmpty,
    WriteNullStringAsEmpty,
    WriteNullNumberAsZero,
    WriteNullBooleanAsFalse,
    SkipTransientField,
    SortField,
    /** @deprecated */
    @Deprecated
    WriteTabAsSpecial,
    PrettyFormat,
    WriteClassName,
    DisableCircularReferenceDetect,
    WriteSlashAsSpecial,
    BrowserCompatible,
    WriteDateUseDateFormat,
    NotWriteRootClassName,
    /** @deprecated */
    DisableCheckSpecialChar,
    BeanToArray,
    WriteNonStringKeyAsString,
    NotWriteDefaultValue,
    BrowserSecure,
    IgnoreNonFieldGetter,
    WriteNonStringValueAsString,
    IgnoreErrorGetter,
    WriteBigDecimalAsPlain,
    MapSortField;

    /**
     * 省略其它代码
     * /
}

你可能感兴趣的:(java,json,jsonobject)