jsonexception:类型java.lang.String无法转换为JSONObject

时间:2013-01-08 06:21:07

标签: java

我遇到了问题,有效的JSON字符串无法成为JSON对象。

当我从浏览器调用我的url时,它返回有效的JSON字符串。请检查

public void initializeHttpClient(){         httpclient = new DefaultHttpClient();         nameValuePairs = new ArrayList(2);     }

public JSONObject sendHttpRequest(String url) {
    try {
        postRequest = new HttpPost(url);
        postRequest.setHeader("Content-type", "application/json");
        postRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));
        httpResponse = httpclient.execute(postRequest);
        httpEntity = httpResponse.getEntity();
        if (httpEntity != null) {
            String responseString = EntityUtils.toString(httpEntity);

//这里出现问题..

            JSONObject responseObject = new JSONObject(responseString);
            return responseObject;
        }
    } catch (Exception e) {
        e.getMessage();
    }
    return null;
}

public JSONObject getLogin(String serviceUrl,String o_email, String o_password,String o_user_id, String o_network_type, String o_format) {
    initializeHttpClient();
    if(serviceUrl!=null){
        nameValuePairs.add(new BasicNameValuePair("login_email",o_email));
        nameValuePairs.add(new BasicNameValuePair("password",o_password));
        nameValuePairs.add(new BasicNameValuePair("user_id",o_user_id));
        nameValuePairs.add(new BasicNameValuePair("network_type",o_network_type));
        nameValuePairs.add(new BasicNameValuePair("format",o_format));
        return sendHttpRequest(serviceUrl);
    }
    return null;
}

2 个答案:

答案 0 :(得分:1)

字符串,例如"Hello There"是无效的JSON。如果您想要防止这种情况发生,您可以随时用

包装您的回复
responseString = "{ \"result\" : " + responseString + " }";

然后将其传递给JSONObject,它将始终正确解析

答案 1 :(得分:0)

 JSONObject responseObject = new JSONObject(responseString);
如果您的输入不是JSON格式,则

无法转换为JSONObject 异常。检查 responseString 是否是格式正确的JSON对象。