问题
android通过okhttp调用后端接口,对于json返回数据解析, android studio控制台报错
org.json.JSONException: Value Response of type java.lang.String cannot be converted to JSONObject
详细问题
2022-09-25 17:31:52.304 28574-28733/com.example.electronicmall W/System.err: org.json.JSONException: Value Response of type java.lang.String cannot be converted to JSONObject
2022-09-25 17:31:52.304 28574-28733/com.example.electronicmall W/System.err: at org.json.JSON.typeMismatch(JSON.java:112)
2022-09-25 17:31:52.304 28574-28733/com.example.electronicmall W/System.err: at org.json.JSONObject.<init>(JSONObject.java:168)
2022-09-25 17:31:52.304 28574-28733/com.example.electronicmall W/System.err: at org.json.JSONObject.<init>(JSONObject.java:181)
2022-09-25 17:31:52.304 28574-28733/com.example.electronicmall W/System.err: at com.example.electronicmall.test.User.UserNewInfoActivity$1$1.onResponse(UserNewInfoActivity.java:103)
2022-09-25 17:31:52.304 28574-28733/com.example.electronicmall W/System.err: at com.squareup.okhttp.Call$AsyncCall.execute(Call.java:168)
2022-09-25 17:31:52.304 28574-28733/com.example.electronicmall W/System.err: at com.squareup.okhttp.internal.NamedRunnable.run(NamedRunnable.java:33)
2022-09-25 17:31:52.304 28574-28733/com.example.electronicmall W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
2022-09-25 17:31:52.304 28574-28733/com.example.electronicmall W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
2022-09-25 17:31:52.304 28574-28733/com.example.electronicmall W/System.err: at java.lang.Thread.run(Thread.java:929)
2022-09-25 17:32:27.455 28574-28596/com.example.electronicmall W/System: A resource failed to call close.
解决方案
对于json数据解析时,删除源字符串中的隐藏字符
即
JSONObject(json.substring(json.indexOf(“{”), json.lastIndexOf(“}”) + 1));
对于笔者而言
将
String responseData = response.body().string();
JSONObject jsonObject = new JSONObject(responseData);
改为
String responseData = responseData1.substring(responseData1.indexOf("{"), responseData1.lastIndexOf("}") + 1);
JSONObject jsonObject = new JSONObject(responseData);
即可
原因
由于在编写String时添加了不需要的字符。使用return new JSONObject(json.substring(json.indexOf(“{”),json.lastIndexOf“}”)+1);删除源字符串中的隐藏字符。
参考文献
JSONException: Value of type java.lang.String cannot be converted to JSONObject
原创不易
转载请标明出处
如果对你有所帮助 别忘啦点赞支持哈