Unable to evaluate the expression Method threw ‘net.sf.json.JSONException‘ exception.

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);
}

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值