之前在使用fastjson进行接口传输数据时,碰到接收端数据转换异常问题,难了我好久。例如:我们需要将json转换成实例集合
{
"SenaHost": [{
"aud_date": 1599445916000,
"aud_user": 0,
"create_date": 1599445916000,
"delete_flag": 0,
"depart_id": 1,
"host_group_id": 2,
"host_img": "images/later/network/2013.png",
"host_ip": "192.168.0.102",
"host_name": "书香中国",
"host_port": 80,
"host_state": 1,
"host_type": 1,
"host_username": "root",
"id": 109,
"isAutoRepair": "",
"monitorType": "SNMP, PING, SOCKET",
"open_state": 0,
"orderId": 0,
"snmp_agreement": 2,
"snmp_key": "ZHtsgjsb",
"snmp_port": 161,
"update_date": 1656392695000,
"ws_user": 48
},
{
"aud_date": 1609736604000,
"aud_user": 0,
"create_date": 1609736604000,
"delete_flag": 1,
"depart_id": 1,
"host_img": "images/later/network/2013.png",
"host_ip": "172.126.14.56",
"host_name": "办公虚拟化交换机",
"host_port": 80,
"host_state": 1,
"host_type": 1,
"host_username": "root",
"id": 136,
"isAutoRepair": "",
"monitorType": "PING, SOCKET",
"open_state": 0,
"orderId": 0,
"snmp_agreement": 2,
"snmp_key": "",
"snmp_port": 161,
"update_date": 1641352585000,
"ws_user": 48
}
],
"num": 44,
"key": "/v7rdUMLOMhlewAkcynNuzqDOGufDDQ="
}
通常对JSON对象的转换操作是使用强转
JSONObject reqData = JSON.parseObject(hostDataStr);
String token = (String) reqData.get("token");
Integer num = (Integer) reqData.get("num");
导致一些朋友对实例对象的操作也是进行强转如下
List<SenaHost> list = (List<SenaHost>) reqData.get("SenaHost");
for (SenaHost senaHost : list) {
System.out.println("senaHost = " + senaHost);
}
这样的话我们在对 list 操作时就会报类似如下错误
java.lang.ClassCastException: com.alibaba.fastjson.JSONObject cannot be cast to com.sd.dev.model.SenaHost
所以之后我就进行大量的查找原因,后来看到说对于实例对象不能直接进行直接强转,需要反序列化。然后我就进行了如下蠢逼操作我还想着那它既然不能强转那应该是没有直接把整个json集合进行反序列化的方法,不然它为啥不直接给我强转了,还要我自己转干啥= =!
文章来源:https://www.toymoban.com/news/detail-694849.html
JSONArray data = (JSONArray) reqData.get("SenaHost");
for (Object datum : data) {
SenaHost senaHost = (SenaHost) json2Object((byte[]) datum, SenaHost.class);
}
// 上面的代码是另一个方法里的,这里贴一起为了方便看
private Object json2Object(byte[] bytes, Class clazz) {
try {
// 反序列化
if (bytes == null) {
return null;
} else {
String jsonObject = (String) JSON.parse(bytes);
return JSON.parseObject(jsonObject, clazz);
}
} catch (Exception e) {
System.out.println("(异常) SenaHostBusiness.json2Object 异常:" + e.getMessage());
}
return null;
}
然而是我想多了它还真有直接反序列化集合的方法0…0文章来源地址https://www.toymoban.com/news/detail-694849.html
正确转换方式如下方式
List<SenaHost> list = JSON.parseArray(reqData.getString("SenaHost"), SenaHost.class);
到了这里,关于ClassCastException: com.alibaba.fastjson.JSONObject cannot be cast to 接口json数据转换异常。的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!