2012-02-20 91 views
0

我有一個問題,試圖在其中有超過89個項目的android中構建JSONArray。它適用於89個項目,但一旦我把90或更多,我得到錯誤「jsonexception預期:之後」。我還是很新的android和java的東西,所以如果更多的錯誤細節,我可以找到這將幫助,讓我知道如何做到這一點。我不認爲這個問題是與JSON本身,因爲當我確認它是從url本身有效的JSON。我將發佈下面的代碼。構建超過89個項目的JSONArray

   HttpGet request = new HttpGet(SERVICE_URL + "/GetResListNoStatus/" + FacID); 
      request.setHeader("Accept", "application/json"); 
      request.setHeader("Content-type", "application/json"); 

      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpResponse response = httpClient.execute(request); 

      HttpEntity responseEntity = response.getEntity(); 

      // Read response data into buffer 
      char[] buffer = new char[(int)responseEntity.getContentLength()]; 
      InputStream stream = responseEntity.getContent(); 
      InputStreamReader reader = new InputStreamReader(stream); 
      reader.read(buffer); 
      stream.close(); 

       //this line here is where the error is occuring 
      JSONArray plates = new JSONArray(new String(buffer)); 

如果有人有任何想法,我真的很感謝任何人都可以給的幫助。謝謝。

回答

4

你只在你的InputStream上調用read()一次。這將讀取任何可用的數據,這可能是所有的請求或只是幾個字節。您需要重複調​​用read(buffer),將讀取的內容附加到固定緩衝區(您可以將它寫入ByteArrayOutputStream中),並在read()返回-1時停止。

編輯

嘗試這樣的事情。

public static void main(String[] args) { 
    try { 
     URL url = new URL("http://www.google.com"); 

     InputStream is = url.openStream(); 

     ByteArrayOutputStream os = new ByteArrayOutputStream(); 

     byte[] buffer = new byte[1024]; 

     int count; 
     while ((count = is.read(buffer)) != -1) { 
      os.write(buffer, 0, count); 
     } 

     is.close(); 

     String json = new String(os.toByteArray()); 

     System.out.println(json); 
    } catch (MalformedURLException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 
+0

所以我會把讀取在一個do while循環直到讀取= -1?那是你的意思嗎? – bflosabre91 2012-02-20 16:07:39

+0

完美運作。非常感謝你的幫助。 – bflosabre91 2012-02-20 16:38:26

1

我相信你得到的錯誤可能是整個信息沒有被收到。

寫出logcat的「new String(buffer)」。