Ответ Android Parse JSON на форматированный вывод - PullRequest
0 голосов
/ 08 октября 2019

Я пытаюсь получить ответ JSON в моем приложении для Android в виде отформатированного файла вместо одной длинной строки. Я следовал 2 урокам (где один работает, см. Ниже), но я не понимаю, где я иду не так. Любая помощь приветствуется.

вот что у меня есть:

private void parseJson(String key) {

        final JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, key.toString(), null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        String title ="";
                        String author ="";
                        String publishedDate = "Not Available";
                        String description = "No Description";
                        int pageCount = 1000;
//                        String categories = "No categories Available ";
                        String category = "No categories Available ";
                        String buy ="";
                        String volumeInfoString = "";
                        String bookJSONString = null;


                        BufferedReader reader = null;


                        String price = "NOT_FOR_SALE";
                        try {
                            JSONArray items = response.getJSONArray("items");

                            for (int i = 0 ; i< items.length() ;i++){
                                JSONObject item = items.getJSONObject(i);
                                JSONObject volumeInfo = item.getJSONObject("volumeInfo");
                                volumeInfoString = item.getJSONObject("volumeInfo").toString();


                                // Get the InputStream.
//                                InputStream inputStream = volumeInfoString.
                                InputStream is = new ByteArrayInputStream( volumeInfoString.getBytes());

                                // Read the response string into a StringBuilder.
                                StringBuilder builder = new StringBuilder();

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

                                String line;
                                while ((line = reader.readLine()) != null) {
                                    // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
                                    // but it does make debugging a *lot* easier if you print out the completed buffer for debugging.
                                    builder.append(line + "\n");  // **Should be formatting it here**
                                }




try{
                                    title = volumeInfo.getString("title");

                                    JSONArray authors = volumeInfo.getJSONArray("authors");
                                    if(authors.length() == 1){
                                        author = authors.getString(0);
                                    }else {
                                        author = authors.getString(0) + "|" + authors.getString(1);
                                    }


                                    publishedDate = volumeInfo.getString("publishedDate");
                                    pageCount = volumeInfo.getInt("pageCount");



                                    JSONObject saleInfo = item.getJSONObject("saleInfo");
                                    JSONObject listPrice = saleInfo.getJSONObject("listPrice");
                                    price = listPrice.getString("amount") + " " +listPrice.getString("currencyCode");
                                    description = volumeInfo.getString("description");
                                    buy = saleInfo.getString("buyLink");
//                                    categories = volumeInfo.getJSONArray("categories").getString(0);


                                    JSONArray categories = volumeInfo.getJSONArray("categories");
                                    if(categories.length() == 1){
                                        category = categories.getString(0);
                                    }else {
                                        category = categories.getString(0) + "|" + categories.getString(1);
                                    }

                                    /*
                                    ***MODEL BELOW***
                                    JSONArray authors = volumeInfo.getJSONArray("authors");
                                    if(authors.length() == 1){
                                        author = authors.getString(0);
                                    }else {
                                        author = authors.getString(0) + "|" + authors.getString(1);
                                    }
                                     */



                                }catch (Exception e){

                                }
                                String thumbnail = volumeInfo.getJSONObject("imageLinks").getString("thumbnail");
//                                Log.d(LOG_TAG, "onResponse: " + items);

                                String previewLink = volumeInfo.getString("previewLink");
                                String url = volumeInfo.getString("infoLink");


                                mBooks.add(new Book2(title , author , publishedDate , description ,category
                                        ,thumbnail,buy,previewLink,price,pageCount,url, volumeInfoString));


                                mSearchViewRecyclerViewAdapter = new SearchViewRecyclerViewAdapter(MainActivity2.this , mBooks);
                                mRecyclerView.setAdapter(mSearchViewRecyclerViewAdapter);
                            }


                        } catch (JSONException e) {
                            e.printStackTrace();
                            Log.e("TAG" , e.toString());

                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });
        mRequestQueue.add(request);
    }

этот код, кажется, без проблем форматирует:

protected String doInBackground(String... params) {

        // Get the search string
        String queryString = params[0];


        // Set up variables for the try block that need to be closed in the finally block.
        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;
        String bookJSONString = null;

        // Attempt to query the Books API.
        try {
            // Base URI for the Books API.
            final String BOOK_BASE_URL =  "https://www.googleapis.com/books/v1/volumes?";

            final String QUERY_PARAM = "q"; // Parameter for the search string.
            final String MAX_RESULTS = "maxResults"; // Parameter that limits search results.
            final String PRINT_TYPE = "printType"; // Parameter to filter by print type.

            // Build up your query URI, limiting results to 10 items and printed books.
            Uri builtURI = Uri.parse(BOOK_BASE_URL).buildUpon()
                    .appendQueryParameter(QUERY_PARAM, queryString)
                    .appendQueryParameter(MAX_RESULTS, "10")
                    .appendQueryParameter(PRINT_TYPE, "books")
                    .build();

            URL requestURL = new URL(builtURI.toString());

            // Open the network connection.
            urlConnection = (HttpURLConnection) requestURL.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();

            // Get the InputStream.
            InputStream inputStream = urlConnection.getInputStream();

            // Read the response string into a StringBuilder.
            StringBuilder builder = new StringBuilder();

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

            String line;
            while ((line = reader.readLine()) != null) {
                // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
                // but it does make debugging a *lot* easier if you print out the completed buffer for debugging.
                builder.append(line + "\n");
            }

            if (builder.length() == 0) {
                // Stream was empty.  No point in parsing.
                // return null;
                return null;
            }
            bookJSONString = builder.toString();

            // Catch errors.
        } catch (IOException e) {
            e.printStackTrace();

            // Close the connections.
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }

        // Return the raw response.


        Log.d(LOG_TAG, "doInBackground: " + bookJSONString);
        return bookJSONString;
//        Log.d(NewBookActivity., "doInBackground: ");
    }
...