json格式字符串含有null值,用JSONArray.fromObject转换为json数组时报错
—————————————————————————————————
问题出现
一天突然发现平时正常运行的平台出错了。测试时发现报错
Could not write JSON: null object; nested exception is com.fasterxml.jackson.databind.JsonMappingException: null object (through reference chain: java.util.HashMap["data"]->java.util.HashMap["list"]->net.sf.json.JSONArray[0]->net.sf.json.JSONObject["id"])
问题出在这个第三方api的返回内容
{
"page": {
"total": 3,
"page": 0,
"size": 10
},
"data": [
{
"id": null,
"deviceSerial": "C95252223",
...
},
{
"id": null,
"deviceSerial": "D43652769",
...
},
...
],
"code": "200",
"msg": "操作成功!"
}
多了“id”字段且它的值为null(之前用这个api是没有这个字段的,所以一直没出错)。
解析不了,于是转换过程中就出错了。
//sr为上面的返回内容
JSONObject json = JSONObject.fromObject(sr);
if(Integer.parseInt(json.get("code").toString()) == 200 ){
responseMap.put("list", JSONArray.fromObject(json.get("data")));//这里出错
responseMap.put("page", JSONObject.fromObject(json.get("page")));
return ResponseData.success(responseMap);
}
问题解决
使用fastjson中的JSON.parseArray()
import com.alibaba.fastjson.JSON;
//sr为返回内容
JSONObject json = JSONObject.fromObject(sr);
if(Integer.parseInt(json.get("code").toString()) == 200 ){
responseMap.put("list", JSON.parseArray(json.get("data").toString()));
responseMap.put("page", JSONObject.fromObject(json.get("page")));
return ResponseData.success(responseMap);
}