关于Fastjson 数组解析异常问题的排查
今日在使用字符串转json的时候,遇到问题,发现转换失败,
报错日志如下:
com.alibaba.fastjson.JSONException: expect '[', but string, pos 8, line 1, column 9"G2京沪高速"
at com.alibaba.fastjson.util.TypeUtils.castToJavaBean(TypeUtils.java:1366)
at com.alibaba.fastjson.util.TypeUtils.cast(TypeUtils.java:932)
at com.alibaba.fastjson.JSONArray.toJavaList(JSONArray.java:450)
at com.hysm.service.impl.OtaProviderServiceImpl.getRoutePriceAndPath(OtaProviderServiceImpl.java:772)
at com.hysm.service.impl.OtaProviderServiceImpl.getResultMessage(OtaProviderServiceImpl.java:187)
at sun.reflect.GeneratedMethodAccessor79.invoke(Unknown Source)
遂紧急排查问题,定位到报错代码如下:
JSONArray paths = json.getJSONObject("route").getJSONArray("paths");
List<Paths> pathsList = paths.toJavaList(Paths.class);
将原始字符串获取下来,线下测试确实无法转换。但是经过测试 发现 原来是获取高德路径规划接口的时候,高德返回参数值不规范。
接口连接:https://restapi.amap.com/v3/direction/driving
此接口的 toll_roal 如果为空则返回列表,有值则返回字符串。
大厂神奇的规范不深做吐槽。
接下来有发现一个有意思的事情:
JSONArray paths = json.getJSONObject("route").getJSONArray("paths");
List<Paths> pathsList = JSON.parseArray(paths.toJSONString(),Paths.class);
此代码又可以正常运行!! why?
都是fastjson提供的方法,为什么会形成差异。
带着问题进入源码,先看 JSONArray.toJavaList。
public <T