2013-06-28 42 views
1

當下載一個JSON數組時,它切斷了字符串的四分之一,它非常大 - 但它應該得到整個字符串。JSON響應中斷部分通過

LogCat中沒有錯誤。這是我正在使用的方法,我已經經歷了幾次,並且無法看到它被切斷的原因。不過,我對此很新。

public static JSONArray getJSONfromURL(String url){ 

    //initialize 
    InputStream is = null; 
    String result = ""; 
    JSONArray jArray = null; 

    //http post 
    try { 

     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost(url);  
     HttpResponse response = httpclient.execute(httppost); 
     HttpEntity entity = response.getEntity(); 

     is = entity.getContent();  

    } catch (Exception e) { 
     Log.e("log_tag", "Error in http connection "+e.toString()); 
    } 
    //convert response to string 

    try { 

     BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 

     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 

     is.close(); 
     result=sb.toString(); 

    } catch (Exception e) {  
     Log.e("log_tag", "Error converting result "+e.toString()); 
    } 
    //try parse the string to a JSON object 

    try { 
     Log.d("log_tag", "jresult: " + result + "finish"); 
     jArray = new JSONArray(result); 

     //Log.e("log_tag", "result: " + jArray.toString()); 

    } catch (JSONException e) { 
     Log.e("log_tag", "Error parsing data "+e.toString()); 
    } 

    return jArray; 
} 

我認爲一旦這個被破解,我將被設置。我會讓這個課程在未來的項目中使用,所以我不需要重建它!

編輯:For循環,其中的標記應添加到地圖:

try{ 
     for(int i=0;i<arrayResultFromURL.length();i++){ 
      JSONObject json_data = arrayResultFromURL.getJSONObject(i); 

      // assign attributes from the JSON string to local variables 
      String id =json_data.getString("id"); 
      String title =json_data.getString("title"); 
      String strap =json_data.getString("strap"); 
      Double lat = (double) json_data.getDouble("lat"); 
      Double lon = (double) json_data.getDouble("long"); 

      theMap.addMarker(new MarkerOptions() 
      .position(new LatLng(lat, lon)) 
      .title(title) 
      .snippet(strap)); 
     } 
    }catch (Exception e){ 
     Log.e("log_tag", "error in array: " + e.toString()); 
    } 
+0

結果返回什麼,預期結果是什麼? – Raghunandan

+0

它應該返回所有此http://pastebin.com/KLr2Czsb,它通過http://pastebin.com/bgSqbNxi –

+0

1/4的方式削減它,我看不出有什麼問題的代碼。嘗試記錄結果並檢查 – Raghunandan

回答

1

也許你的問題來自於您的治療響應對象的方式。檢查這個線程https://stackoverflow.com/a/9192640/665823

如果不嘗試首先檢查響應的大小,看看你是否收到所有。

httpResponse.getEntity().getContentLength() 

而且萬一你不知道有一個很好的庫(我一直在使用它,因爲我發現它),簡化了JSON解析ckeck出來http://jackson.codehaus.org/

0

這些類型的東西能最好由GSON或Jackson等庫完成

此外,如果您的目標是創建一個JSONArray,那麼需要一個構造函數來接受JSONTokener。 JSONTokener可以通過InputStream構造。