我的服务器通过 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。我什至将服务器响应 header 的内容类型更改为“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);
}
:'( :'(
最佳答案
你是怎么做到的?它应该适用于:
JSONObject object = new JSONObject (yourString);
关于java - 来自服务器的字符串无法转换为 JSONObject?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10865118/