java.lang.String类型的值无法转换为JSONObject

时间:2014-09-23 08:39:08

标签: android json http-post

在我的代码中,我试图从服务器访问一些json返回。但是我无法将json从服务器转换为JsonObject。这是我的代码,

result = post.getHttpData(Constants.UrlDepartureCity);
catchLog(result);
JSONObject obj=new JSONObject(result);

我使用自定义catchLog在日志中打印json返回。

09-23 14:53:59.940: I/DepartureCityAsync(23313): 
{"status":"1","departure_city":[
{"entity_id":"1","field_depature_city_tid":"1","entity_type":"node"},
{"entity_id":"8","field_depature_city_tid":"1","entity_type":"node"}, 
{"entity_id":"12","field_depature_city_tid":"1","entity_type":"node"},
{"entity_id":"5","field_depature_city_tid":"2","entity_type":"node"},
{"entity_id":"9","field_depature_city_tid":"2","entity_type":"node"},
{"entity_id":"17","field_depature_city_tid":"2","entity_type":"node"},
{"entity_id":"6","field_depature_city_tid":"3","entity_type":"node"},
{"entity_id":"7","field_depature_city_tid":"5","entity_type":"node"}]}

我复制结果并验证json在http://jsonlint.com/中返回。没有错误,语法也正确。但是当我尝试将其转换为JsonObject时,我收到了这个错误。

09-23 14:53:59.940: W/System.err(23313): org.json.JSONException: Value  of type java.lang.String cannot be converted to JSONObject

我该如何解决这个问题?请。 谢谢

3 个答案:

答案 0 :(得分:1)

我认为你的回归中可能会有一些空白字符。将其更改为 JSONObject obj = new JSONObject(result.trim());

答案 1 :(得分:0)

我认为您的json格式错误或有一些小错误。从this link,您可以找到解决方案。

答案 2 :(得分:0)

final TextView res=(TextView)findViewById(R.id.res);

    try
    {
        HttpClient client=new DefaultHttpClient();
        HttpPost request=new HttpPost("http://192.168.0.30/test.js");
        HttpResponse response=client.execute(request);
        HttpEntity entity=response.getEntity();
        res.setText(EntityUtils.toString(entity));
    }
    catch(Exception e)
    {
        res.setText(e.toString());
    }

这是我的代码示例,它适用于我...对于您提供的相同json。 你能告诉我你的代码如何获得响应。我没有得到你用过的方法getHttpData()。

相关问题