【问题标题】:jsonexception: of type java.lang.String cannot be converted to JSONObjectjsonexception: java.lang.String 类型的无法转换为 JSONObject
【发布时间】:2013-01-09 06:22:28
【问题描述】:

我遇到了一个问题,有效的 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;
}

【问题讨论】:

  • 编程问题应在 StackOverflow.com 中提出。这个问题稍后将由mod移动。 :)
  • 发布异常堆栈跟踪。
  • 您发布的是 JSON 还是 HTTP 表单?您将 Content-Type: 标头设置为 application/json,但您设置了一个 RequestEntity,它生成适合 application/x-www-form-urlencoded 的实体。
  • 你应该发布这个字符串“有效的 JSON 字符串不能成为 JSON 对象”

标签: java


【解决方案1】:

字符串,例如"Hello There" 不是有效的 JSON。如果您想防范这种情况,您可以随时使用

responseString = "{ \"result\" : " + responseString + " }";

然后将它传递给 JSONObject,它总是会正确解析

【讨论】:

    【解决方案2】:
     JSONObject responseObject = new JSONObject(responseString);
    

    无法转换为 JSONObject 如果您的输入不是 JSON 格式,则会引发异常。检查 responseString 是否是格式良好的 JSON 对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-02
      • 2016-11-24
      • 1970-01-01
      • 1970-01-01
      • 2017-02-03
      • 2017-10-02
      相关资源
      最近更新 更多