fastjson WriteNullListAsEmpty 导致 Date 类型序列化受影响

r8xiu3jd  于 2021-11-27  发布在  Java
关注(0)|答案(4)|浏览(316)

在spring-mvc中配置了fastjson序列化:

<mvc:annotation-driven>
    <mvc:message-converters register-defaults="true">
        <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
            <property name="supportedMediaTypes">
                <list>
                    <value>application/json;charset=UTF-8</value>
                </list>
            </property>
            <property name="fastJsonConfig">
                <bean class="com.alibaba.fastjson.support.config.FastJsonConfig">
                    <property name="features">
                        <list>
                            <value>AllowUnQuotedFieldNames</value>
                            <value>DisableCircularReferenceDetect</value>
                        </list>
                    </property>
                    <property name="serializerFeatures">
                        <list>
                            <!-- 将Collection类型字段的字段空值输出为[] -->
                            <value>WriteNullListAsEmpty</value>
                        </list>
                    </property>
                </bean>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

导致Date类型的属性null值时,也输出来了,不加这个WriteNullListAsEmpty配置是不输出null字段的。

7cwmlq89

7cwmlq893#

package t;

import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class Test3 {

    private List list;
    private Date date;

    public List getList() {
        return list;
    }

    public void setList(List list) {
        this.list = list;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public static void main(String[] args) {
//        System.setProperty("java.vm.name", "dalvik");
        String string = JSON.toJSONString(new Test3(), SerializerFeature.WriteNullListAsEmpty);
        System.out.println(string);
    }
}

当使用 "dalvik"跳过asm时,就不会出现 @wenshao

p4tfgftt

p4tfgftt4#

以下是在ASMSerializerFactory使用ASM生成JavaBeanSerializer子类的代码中,对判断值为空的字段处理函数_if_write_null

当一个null字段不是String\Number\Collection\Boolean 时,它的序列化过滤mask是
SerializerFeature.WRITE_MAP_NULL_FEATURES

而WriteNullListAsEmpty 就被包含在 WRITE_MAP_NULL_FEATURES之中

@wenshao 不是很理解,为什么设置了WriteNullBooleanAsFalse、WriteNullListAsEmpty、WriteNullNumberAsZero、WriteNullStringAsEmpty这些feature之后,null字段需要被输出。而且只有在ASM的情况下会这样,而Android不会。

相关问题