alibaba / fastjson

FASTJSON 2.0.x has been released, faster and more secure, recommend you upgrade.
https://github.com/alibaba/fastjson2/wiki/fastjson_1_upgrade_cn
Apache License 2.0
25.76k stars 6.5k forks source link

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

Open warrior701 opened 5 years ago

warrior701 commented 5 years ago

在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字段的。

wenshao commented 5 years ago

什么版本?

Sochene commented 5 years ago

1.2.55

Sochene commented 5 years ago
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

Sochene commented 5 years ago

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

image

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

image 而WriteNullListAsEmpty 就被包含在 WRITE_MAP_NULL_FEATURES之中

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