2013-06-28 41 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构造。