今天遇到一个相当智障的问题,前端传参数到后端,后端直接报json解析错误,not close?? 听着就很奇怪,关键有的时候正常,有的时候不正常。于是先在浏览器中F12,看传的参数 感觉 没问题,在后端filter中获得request的body,打印出来,很长,也看不出来问题。
1、先来看一下用以接收参数的dto
@Data
public class DeliveryFeeProcessDTO extends TDeliveryFeeProcessRecord {/*** 货物明细*/private List<TDeliveryFeeProcessGoodsInfo> goodsList;/*** 文件列表*/private List<FileInfo> fileList;/*** 1 通过* 0 驳回*/private Integer state;
}
项目中配置的是fastjson,1.2.83
http:converters:preferred-json-mapper: fastjson # Json转换器<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.83</version></dependency>
可以看到有两个list 比较可疑··
2、看一下我精简后的json 字符串,这也能报错?
{"creatorId": "superadmin","goodsList": "","fileList": ""}
3、写一个demo
public static void main(String[] args) {
// String json = "{\"creatorId\": \"superadmin\",\"goodsList\": \"\",\"fileList\": []}";dealJson("{\"creatorId\": \"superadmin\",\"goodsList\": \"\"}");dealJson("{\"creatorId\": \"superadmin\",\"fileList\": \"\"}");dealJson("{\"creatorId\": \"superadmin\",\"goodsList\": []}");dealJson("{\"creatorId\": \"superadmin\",\"fileList\": []}");dealJson("{\"creatorId\": \"superadmin\",\"goodsList\": \"\",\"fileList\": []}");dealJson("{\"creatorId\": \"superadmin\",\"goodsList\": \"\",\"fileList\": \"\"}");dealJson("{\"creatorId\": \"superadmin\",\"goodsList\": [],\"fileList\": []}");dealJson("{\"creatorId\": \"superadmin\",\"goodsList\": [],\"fileList\": \"\"}");}private static void dealJson(String json) {Boolean flag = true;try {DeliveryFeeProcessDTO dto = JSONObject.parseObject(json, DeliveryFeeProcessDTO.class);}catch (Exception e){flag = false;
// System.out.println(json);System.out.println(e.getMessage());
// e.printStackTrace();}if(flag){System.out.println("PASS"+json);}else {System.out.println("FAILED"+json);}}
出来的结果是
FAILED{"creatorId": "superadmin","goodsList": ""}
FAILED{"creatorId": "superadmin","fileList": ""}
PASS{"creatorId": "superadmin","goodsList": []}
PASS{"creatorId": "superadmin","fileList": []}
FAILED{"creatorId": "superadmin","goodsList": "","fileList": []}
FAILED{"creatorId": "superadmin","goodsList": "","fileList": ""}
PASS{"creatorId": "superadmin","goodsList": [],"fileList": []}
PASS{"creatorId": "superadmin","goodsList": [],"fileList": ""}
可以看到,应该是因为List不能是空字符串,必须是空数组才行
但是最后一个就很鬼畜了!!竟然PASS了!
好了,省流(我懒得去翻fastjson的源码,更懒得去看fastjson的release note)。解决办法是升级····简单粗暴。在maven仓库中查到最新是2.0.53
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>2.0.53</version></dependency>
所以,每当你以为自己技术还行的时候,就会在小坑里栽跟头