fastjson2 icon indicating copy to clipboard operation
fastjson2 copied to clipboard

[BUG] bean转jsonstring 自动进行方法调用导致异常

Open wszpwsren opened this issue 1 year ago • 3 comments

问题描述

bean转jsonstring时,自动调用了类中的方法 由于类中的方法有可能出现异常,所以,对bean的序列化过程是否不应该调用类内的方法?

环境信息

  • JDK信息: [e.g.:Openjdk 1.8.0_251]
  • 版本信息:[e.g.:Fastjson2 2.0.12]

重现步骤

@Data
public class TermV3 {

    /**
     * 词语
     */
    private String word;

    /**
     * 获取本词语在HanLP词库中的频次
     *
     * @return 频次,0代表这是个OOV
     */
    public int getFrequency() {
        return 1/0;
    }

}

方法

    public static void main(String[] args) {

        TermV2 termV2 = new TermV2();
        System.out.println(JSONObject.toJSONString(termV2));
    }

相关日志输出

Exception in thread "main" java.lang.ArithmeticException: / by zero
	at com.yx.nlp.nlp.hanlp.v2.TermV3.getFrequency(TermV3.java:26)
	at com.alibaba.fastjson2.writer.ObjectWriter_1.write(Unknown Source)
	at com.alibaba.fastjson2.JSON.toJSONString(JSON.java:1757)
	at com.alibaba.fastjson2.JSONObject.toJSONString(JSONObject.java:1085)
	at com.yx.nlp.service.NlpImpl.main(NlpImpl.java:56)

wszpwsren avatar Sep 07 '22 09:09 wszpwsren

https://github.com/alibaba/fastjson2/blob/main/docs/features_cn.md 参考这个JSONWriter.Feature. IgnoreErrorGetter

wenshao avatar Sep 07 '22 22:09 wenshao

https://github.com/alibaba/fastjson2/blob/main/docs/features_cn.md 参考这个JSONWriter.Feature. IgnoreErrorGetter

这个方法并不是一个getter,只是一个以get开头命名的方法 能不能在调用前进行识别呢?

wszpwsren avatar Sep 08 '22 01:09 wszpwsren

https://github.com/alibaba/fastjson2/blob/main/docs/name_filter_cn.md 可以使用NameFilter

wenshao avatar Sep 15 '22 10:09 wenshao

@wszpwsren 也可以用这个JSONWriter.Feature.IgnoreNonFieldGetter

wenshao avatar Mar 04 '23 18:03 wenshao