AsyncTask期间的JSONException

时间:2013-02-23 22:08:08

标签: java android json

@Override
    protected Integer doInBackground(Void... params) 
    {
        String readMyJSON = readMyJSON();
                try {
                  JSONArray jsonArray = new JSONArray(readMyJSON);                    
                } catch (Exception e) {
                  e.printStackTrace(); 
                }
        return 0;
    }

这不起作用,在JSONArray jsonArray = new JSONArray(readMyJSON);期间,发生JSONException。有人能告诉我问题出在哪里?提前谢谢。

P.S。:我使用的方法:

   public String readMyJSON() 
   {
        StringBuilder builder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet("http://search.twitter.com/search.json?q=android");
        try {
          HttpResponse response = client.execute(httpGet);
          StatusLine statusLine = response.getStatusLine();
          int statusCode = statusLine.getStatusCode();
          if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
              builder.append(line);
            }
          } else {
            Log.e(ParseJSON.class.toString(), "Failed to download file");
          }
        } catch (ClientProtocolException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
        return builder.toString();
      }

这种方法似乎没问题。

2 个答案:

答案 0 :(得分:2)

简而言之,来自twitter的响应不是JSON数组,因此您会遇到异常。如果需要结果数组,请执行以下操作:

JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
JSONArray results = object.getJSONArray("results");

我建议你阅读Twitter API docs。具体而言,https://dev.twitter.com/docs/api/1/get/search

答案 1 :(得分:0)

你可以试试这个:

JSONArray jsonArray = new JSONArray("["+readMyJSON+"]"); 

我希望它能起作用。