2019-02-22 接口返回数据转JSON遇到的问题
在工作中调用某接口,返回的数据是String类型的json数据,用net.sf.json的JSONObject.fromObject或FastJson的JSONObject.parseObject都报错。
响应结果的字符串打印显示为:
"{\"code\":0,\"data\":{\"orderNo\":\"22CC26FC06144836A58FCC435DF62186\",\"success\":true},\"desc\":\"成功\",\"sid\":\"0100000319816\",\"success\":true,\"timestamp\":\"20190222225058\"}"
1. 使用net.sf.json
JSONObject result = JSONObject.fromObject(respData);
报错:net.sf.json.JSONException: A JSONObject text must begin with '{' at character 1……
2. 使用FastJson
JSONObject result = JSONObject.parseObject(respData);
报错:java.lang.ClassCastException: java.lang.String cannot be cast to com.alibaba.fastjson.JSONObject
后来在网上查到一篇类似的问题,解决方法是:(1)去掉斜杠;(2)去掉前后的双引号
于是尝试了以下的代码:
// 去掉斜杠\
respData= respData.replace("\\", "");
logger.info("去掉斜杠:" + respData);
// 去掉前后的双引号
respData= respData.substring(1, respData.length() - 1);
logger.info("去掉前后双引号:" + respData);
响应结果:"{\"code\":0,\"data\":{\"orderNo\":\"22CC26FC06144836A58FCC435DF62186\",\"success\":true},\"desc\":\"成功\",\"sid\":\"0100000319816\",\"success\":true,\"timestamp\":\"20190222225058\"}"
去掉斜杠:"{"code":0,"data":{"orderNo":"22CC26FC06144836A58FCC435DF62186","success":true},"desc":"成功","sid":"0100000319816","success":true,"timestamp":"20190222225058"}"
去掉前后的双引号:{"code":0,"data":{"orderNo":"22CC26FC06144836A58FCC435DF62186","success":true},"desc":"成功","sid":"0100000319816","success":true,"timestamp":"20190222225058"}
然后再用JSONObject result = JSONObject.parseObject(respData); 就不报错了。