加载JSON-Array失败

时间:2013-07-05 13:55:03

标签: java android json

我作为HTTP-Response获得的JSON-String / Array在一行中,如下所示:

[{
        "haendlerName": "Zielpunkt",
        "shops": [{
            "shopId": 243779,
            "ort": "Wien",
            "strasse": "Erdbergstraße 61",
            "plz": "1030",
            "lat": 48.19867,
            "lon": 16.400263,
            "distance": 0.14937061106081023,
            "openinghours": null
        }],
        "imageLink": "http://images.schnapp.at/images/zielpunkt__e349e2a937b5bf4f78e0fb3063b1fca8.png",
        "account_id": 171619
    }, ...
我正在加载它:

HttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
response = httpclient.execute(httpGet);
HttpEntity resEntity = response.getEntity(); 
String response2=EntityUtils.toString(resEntity);
JSONArray finalResult = new JSONArray(response2);

编辑:工作版!

HttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);    
response = httpclient.execute(httpGet);
String json = EntityUtils.toString(response.getEntity());
finalResult = new JSONArray(json);

但是在最后一行它崩溃了,只有我得到的错误是NullPointerException。 我检查了tokener的内容,似乎很好。 还检查了整个输入(来自http响应的String),它是一个有效的JSON字符串。

值得一提的是,主数组中的JSONObjects还包含一个子数组。

任何想法可能导致崩溃的原因?或者我做错了什么?

1 个答案:

答案 0 :(得分:1)

删除BufferedReaderString jsonJSONTokener tokener。试试这种方式

String json = EntityUtils.toString(response.getEntity());
JSONArray finalResult = new JSONArray(json);

EntityUtils.toString读取Entity的内容并将其作为String

返回

你应该替换:

BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
    String json = reader.readLine();
    JSONTokener tokener = new JSONTokener(json);
    JSONArray finalResult = new JSONArray(tokener);

String json = EntityUtils.toString(response.getEntity());
JSONArray finalResult = new JSONArray(json);