JSON响应部分切断

时间:2013-06-28 15:00:37

标签: java android json

下载JSON数组时,它会切断字符串的1/4,非常大 - 但它应该得到整个字符串。

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;
}

我认为一旦破裂,我就会被设定。我会把它作为一个类在未来的项目中使用,所以我不必继续重建它!

编辑:对于应将标记添加到地图的循环:

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());
    }

2 个答案:

答案 0 :(得分:1)

也许您的问题来自您对待响应对象的方式。检查此帖子https://stackoverflow.com/a/9192640/665823

如果没有尝试先检查响应的大小,看看你是否正在接收所有响应。

httpResponse.getEntity().getContentLength()

另外,如果您不知道有一个很好的库(我已经使用它,因为我发现它)简化了json解析ckeck it out http://jackson.codehaus.org/

答案 1 :(得分:0)

这些类型的东西最好由GSON或Jackson等图书馆完成

此外,如果您的目标是创建JSONArray,则会有一个构造函数接收JSONTokener。 JSONTokener又可以从您的InputStream构建。