作者:贺子江
- 背景介绍
本篇文章是在项目迭代的过程中,发现了的一个有趣的bug所引发出来的源码分析,在这里以点破面,研究一下fastjson的源码 - 案例分析
2.1 发现问题的过程
在项目使用中,发现对于Timestamp的类型进行toJSONString()方法调用的时候,输出结构并没有按照预想的接果进行展示,后续单独拆出demo来进行研究
public static void main(String[] args) {
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
JSONObject jsonObject = new JSONObject();
jsonObject.put(“timestamp”,timestamp);
System.out.println(jsonObject.toJSONString());
}
预期:输出Timestamp类的tostring信息
实际:输出的是Timestamp的时间戳long值
2.2 debug过程和代码分析
当我们遇到和我们想法不一样的时候,就要去看源码到底是怎么实现的。在这里我的第一反应是fastjson的bug,然后我们要去验证这是fastjson的bug还是说这是它自己的策略
调用栈追踪
public String toJSONString() {
SerializeWriter out = new SerializeWriter();
String var2;
try {
(new JSONSerializer(out)).write(this);
var2 =