我的服务器通过 HTTP POST 响应的主体返回一个 JSON 对象,但是当我的应用程序尝试将字符串转换为 JSONObject 时出现此错误:
06-02 09:05:34.380: E/JSONException_MyAppService(19913): org.json.JSONException: Value {"VALS":{"VAL1":"hello","VAL2":"hello2","VAL3":"hello3"}} of type java.lang.String cannot be converted to JSONObject
看起来我的服务器正在返回可接受的 JSON 编码字符串,但它不会转换为 JSONObject。我什至将服务器响应头的内容类型更改为“application/json”。请帮我解决这个问题,我一直在尝试一整天。
编辑-我使用以下代码:
try {
ResponseHandler<String> responseHandler=new BasicResponseHandler();
String responseBody = client.execute(post, responseHandler);
JSONObject response=new JSONObject(responseBody);
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("ClientProtocol_"+TAG,""+e);
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("IO_"+TAG,""+e);
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("JSONException_"+TAG,""+e);
}
我还尝试了 imran khan 的建议:
try {
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
if (entity != null) {
String retSrc = EntityUtils.toString(entity);
// parsing JSON
JSONObject result = new JSONObject(retSrc); //Convert String to JSON Object
JSONArray tokenList = result.getJSONArray("VALS");
JSONObject oj = tokenList.getJSONObject(0);
String token = oj.getString("VAL1");
String token1 = oj.getString("VAL2");
String token11 = oj.getString("VAL3");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("ClientProtocol_"+TAG,""+e);
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("IO_"+TAG,""+e);
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("JSONException_"+TAG,""+e);
}
:'( :'(