解析android中的json对象时出现异常

时间:2015-10-03 07:52:42

标签: android json parsing

我正在连接到一个url,以便检索json数据然后解析它。 这是我的代码

protected String doInBackground(Object... params) {
    int responsecode = -1;
    try {
        URL HeadingUrl = new URL("http://blog.teamtreehouse.com/api/get_recent_summary/?count=10"); // Create a URL object
        HttpURLConnection connection = (HttpURLConnection) HeadingUrl.openConnection();   //we would make a connection object so as to connect to the url
        connection.connect();   // connection to the required url & also may throw IO exception

        responsecode = connection.getResponseCode();

        if (responsecode == HttpURLConnection.HTTP_OK) {
            InputStream inputStream = connection.getInputStream(); // catching the data in an input stream as it can be of any type
            Reader reader = new InputStreamReader(inputStream); //reading the inputstream byte by byte
            int contentLength = connection.getContentLength(); // creating size so as to store data which will be character by character
            char[] charArray = new char[contentLength]; //character array to store data
            reader.read(charArray); // reading from inputStream and storing in char array
            String responseData = new String(charArray); //converting char into string


            JSONObject jsonResponse = new JSONObject(responseData);
            String status = jsonResponse.getString("status"); // for a test
            Log.v(TAG, status); // for a test purpose

            JSONArray jsonArray = jsonResponse.getJSONArray("posts");
            for (int i = 0; i <= jsonArray.length(); i++) {
                JSONObject individualPost = jsonArray.getJSONObject(i);
                String title = individualPost.getString("title");
                Log.v(TAG, "title" + i + ":" + " loop ");

            }

        } else {
            Log.i(TAG, "Unsuccesful Code is :" + responsecode);
        }
    } catch (MalformedURLException e) {
        Log.e(TAG, "Exception caught ", e);
    } catch (IOException e) {
        Log.e(TAG, "Exception Caught ", e);
    } catch (Exception e) {
        Log.e(TAG, "Exception caught ", e);
    }
    return "Code : " + responsecode;
}

将responseData中的json数据作为字符串获取后,我无法解析它,并且它正在捕获异常(第3个catch块),你能告诉我们是什么问题以及如何解决这个问题。 感谢

1 个答案:

答案 0 :(得分:0)

我认为您的问题在于读取输入流.try我的函数来读取输入流。

public static  String getTextFromStream(InputStream inputstream)throws IOException{

    StringBuilder total = new StringBuilder();
    String line="";

    BufferedReader reader = new BufferedReader(new InputStreamReader(inputstream));


        while ((line = reader.readLine()) != null) {
            total.append(line);
        }

    return total.toString();
}

像这样使用它:

String responseData=getTextFromStream(inputStream);