FastJson库省略小数点后0的Bug的跟踪
但是我们在使用中,发现一个Bug:
我们的接口中定义了某个float类型的参数,但是如果传过来的值的小数点后面为0的话(比如12.0),那么“.0”会被省略掉。而这一点是我们不能接受的。
下面对此Bug详细说明,比如代码如下:
com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
json.put("phone", "13911112222");
json.put("authCode","285345");
json.put("deviceType", "phone");
json.put("myvalue", 12.0);
String json1 = json.toString();
System.out.println("JSON-->"+json1);如上代码,myvalue参数的值是12.0,但是此代码输出的结果是:JSON-->{"authCode":"285345","deviceType":"phone","myvalue":12,"phone":"13911112222"}可见,“.0”被省略掉了。跟踪FastJson库的源码,发现JSONObject类继承自JSON类,而且toString()方法直接继承父类的方法,未做覆盖,继续查看JSON类的toString()方法,发现是这样的:
@Override
public String toString() {
return toJSONString();
}直接调用了toJSONString()方法。而toJSONString()方法又是这样的: public String toJSONString() {
SerializeWriter out = new SerializeWriter();
try {
new JSONSerializer(out).write(this);
return out.toString();
} finally {
out.close();
}
}继续追查,查看SerializeWriter类的源码,找到writeFloatAndChar()方法,代码如下: public void writeFloatAndChar(float value, char c) {
String text = Float.toString(value);
if (text.endsWith(".0")) {
text = text.substring(0, text.length() - 2);
}
write(text);
write(c);
}终于定位到原因了,对于JSON值的浮点数,如果是以“.0”结尾的,直接截断这个结尾,所以就有了本文开头的一幕。结论:虽然这个不完全算是Bug,但是这种省略浮点数的“.0”结尾,有时候不能满足业务需求。
原文地址:http://blog.csdn.net/chszs/article/details/45854959