fastjson AfterFilter和BeforeFilter添加JavaBean对象报错

rggaifut  于 2022-11-02  发布在  Java
关注(0)|答案(1)|浏览(160)

fastjson版本:1.2.79
jdk版本:1.8
错误信息:Filter里加两个对象报错
Exception in thread "main" java.lang.NullPointerException at com.alibaba.fastjson.serializer.AfterFilter.writeKeyValue(AfterFilter.java:24) at com.xxlcx.fastjson.vo.filter.RefAfterFilterTest.writeAfter(RefAfterFilterTest.java:29) at com.alibaba.fastjson.serializer.AfterFilter.writeAfter(AfterFilter.java:16) at com.alibaba.fastjson.serializer.JSONSerializer.writeAfter(JSONSerializer.java:507)
测试代码:
`package com.xxlcx.fastjson.vo.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.AfterFilter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xxlcx.fastjson.vo.DeptVO;
import com.xxlcx.fastjson.vo.UserVO;

import java.util.ArrayList;
import java.util.List;

public class RefAfterFilterTest extends AfterFilter {

private DeptVO dept = new DeptVO(1,"afterDeptName");

@Override
public void writeAfter(Object object) {

    if(object instanceof UserVO){

        this.writeKeyValue("afterFilterOne",dept);
        /*多加一个属性报错,原因是dept是object也触发了writeAfter,当前线程变量serializer被设置为null了serializerLocal.set(null);
         *这两个write换个顺序就不会报错
         */
        this.writeKeyValue("afterFilterTwo","two");

       // this.writeKeyValue("afterFilterThree",dept);
    }
}

public static void main(String[] args) {
    RefAfterFilterTest refAfterFilterTest = new RefAfterFilterTest();

    List<UserVO> users = new ArrayList<>(2);
    users.add(new UserVO(0,"a",0));
    users.add(new UserVO(1,"b",1));

    //这里会出现{"$ref":"$[0].null"} null问题
    System.out.println(JSON.toJSONString(users,refAfterFilterTest));
    System.out.println(JSON.toJSONString(users,refAfterFilterTest, SerializerFeature.DisableCircularReferenceDetect));

}

}
`
fastjson.zip

4zcjmb1e

4zcjmb1e1#

您好,我对这个问题有一些想法,请给我一些时间去解决

相关问题