java - 来自服务器的字符串无法转换为 JSONObject?

标签 java android json http

我的服务器通过 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/

相关文章:

java - 使用 GSON,当某些键具有特殊字符时如何将 JSON 转换为 Java

java - 复杂类型到新类名的 JAXB 绑定(bind)

android - 获取 JSON 响应 Android

android - 从没有开启Root的设备中的 Assets 文件夹复制数据库

java - 如何使用findViewById获取ListView

java - 为什么java中无法提取Json数组?

php条件从json数据中过滤结果

java - 如何在基于 Java 的应用程序服务器上使用 GCM 向 iOS 设备发送推送通知

java - java 中的 windowOpened 不工作

java - 是否有用于 Spring JDBCTemplate 代码生成的 Eclipse 插件?