从解析的JSON字符串

时间:2016-10-30 06:40:37

标签: java android json

到目前为止,我的图书清单代码运行良好。我稍后会发布网址请求,我现在正在处理这项功能。但是,这是我输出的Screenshot。它的作用是,对于我的作者部分,作者的名字用方形打印打印,成熟度等级用大写字母和下划线打印。我还没有能够以更加用户友好的方式弄清楚如何编辑输出。

以下是我的Java类。

MainActivity.java

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ArrayList<Books> books = BookUtils.extractBooks();

        // Find a reference to the {@link ListView} in the layout
        ListView bookListView = (ListView) findViewById(R.id.list);

        // Create a new {@link ArrayAdapter} of earthquakes
        BookAdapter adapter = new BookAdapter(this, books);

        // Set the adapter on the {@link ListView}
        // so the list can be populated in the user interface
        bookListView.setAdapter(adapter);
    }
}

BookAdapter.java

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.List;


public class BookAdapter extends ArrayAdapter<Books> {

    public BookAdapter(Context context, List<Books> books){
        super(context, 0, books);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        View listItemView = convertView;
        if (listItemView == null){
            listItemView = LayoutInflater.from(getContext()).inflate(R.layout.book_list_item, parent, false);
        }

        Books currentBook = getItem(position);

        TextView title = (TextView)listItemView.findViewById(R.id.book_title);
        title.setText(currentBook.getTitle());

        TextView authors = (TextView)listItemView.findViewById(R.id.book_author);
        authors.setText(currentBook.getAuthors());

        TextView publisher = (TextView)listItemView.findViewById(R.id.book_publisher);
        publisher.setText(currentBook.getPublisher());

        TextView publishingDate = (TextView)listItemView.findViewById(R.id.book_publishing_date);
        publishingDate.setText(currentBook.getPublishedDate());

        TextView language = (TextView)listItemView.findViewById(R.id.book_language);
        language.setText(currentBook.getLanguage());

        TextView pageCount = (TextView)listItemView.findViewById(R.id.book_page_count);
        pageCount.setText(currentBook.getCount());

        TextView printType = (TextView)listItemView.findViewById(R.id.book_print_type);
        printType.setText(currentBook.getPrintType());

        TextView maturityRating = (TextView)listItemView.findViewById(R.id.book_maturity_rating);
        maturityRating.setText(currentBook.getMaturityRating());

        return listItemView;
    }
}

Books.java

public class Books {
    private String mTitle;
    private String mAuthors;

    private String mPublisher;
    private String mPublishingDate;
    private String mLanguage;

    private String mCount;
    private String mPrintType;
    private String mMaturityRating;

    public Books(String title, String authors, String publisher, String publishingDate, String language, String count, String printType, String maturityRating) {
        mTitle = title;
        mAuthors = authors;

        mPublisher = publisher;
        mPublishingDate = publishingDate;
        mLanguage = language;

        mCount = count;
        mPrintType = printType;
        mMaturityRating = maturityRating;
    }

    public String getTitle() {return mTitle;}
    public String getAuthors(){return mAuthors;}

    public String getPublisher(){return mPublisher;}
    public String getPublishedDate(){return mPublishingDate;}
    public String getLanguage(){return mLanguage;}

    public String getCount(){return mCount;}
    public String getPrintType(){return mPrintType;}
    public String getMaturityRating(){return mMaturityRating;}
}

BookUtils.java

import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public final class BookUtils {

    private static final String SAMPLE_JSON_RESPONSE = "{\n" +
            " \"kind\": \"books#volumes\",\n" +
            " \"totalItems\": 1117,\n" +
            " \"items\": [\n" +
            "  {\n" +
            "   \"kind\": \"books#volume\",\n" +
            "   \"id\": \"IEk2m00o9_IC\",\n" +
            "   \"etag\": \"+odAmEu8Vk0\",\n" +
            "   \"selfLink\": \"https://www.googleapis.com/books/v1/volumes/IEk2m00o9_IC\",\n" +
            "   \"volumeInfo\": {\n" +
            "    \"title\": \"Android Apps Security\",\n" +
            "    \"authors\": [\n" +
            "     \"Sheran Gunasekera\"\n" +
            "    ],\n" +
            "    \"publisher\": \"Apress\",\n" +
            "    \"publishedDate\": \"2012-09-12\",\n" +
            "    \"description\": \"Android Apps Security provides guiding principles for how to best design and " +
            "develop Android apps with security in mind. It explores concepts that can be used to secure apps and how " +
            "developers can use and incorporate these security features into their apps. This book will provide developers with " +
            "the information they need to design useful, high-performing, and secure apps that expose end-users to as little risk " +
            "as possible. Overview of Android OS versions, features, architecture and security. Detailed examination of areas where " +
            "attacks on applications can take place and what controls should be implemented to protect private user data In-depth guide " +
            "to data encryption, authentication techniques, enterprise security and applied real-world examples of these concepts What you’ll " +
            "learn How to identify data that should be secured How to use the Android APIs to ensure confidentiality and integrity of data " +
            "How to build secure apps for the enterprise About Public Key Infrastructure, encryption APIs and how to implement them in apps " +
            "About owners, access control lists and permissions to allow user control over App properties About client-server apps and how to manage " +
            "authentication, transport layer encryption and server-side security Who this book is for This book is for intermediate and experienced Android " +
            "app developers that are already familiar with writing apps from scratch. It discusses mechanisms on how apps can be secured so that private, end-user " +
            "data is kept secure on the device and while in transit. If you’re just embarking on the path to Android development, then this book " +
            "may prove to be a useful companion to other developer guides. Table of Contents Android Architecture & Security Controls " +
            "The Foundation of an App Who Has Access? Designing and Developing 3 Sample Apps Using PKI & Encryption Interfacing with Web " +
            "Services Writing for the Enterprise Designing and Developing 3 More Sample Apps Publishing and Selling Your Apps Malware, Spyware " +
            "and Your End-User API Reference\",\n" +
            "    \"industryIdentifiers\": [\n" +
            "     {\n" +
            "      \"type\": \"ISBN_13\",\n" +
            "      \"identifier\": \"9781430240624\"\n" +
            "     },\n" +
            "     {\n" +
            "      \"type\": \"ISBN_10\",\n" +
            "      \"identifier\": \"1430240628\"\n" +
            "     }\n" +
            "    ],\n" +
            "    \"readingModes\": {\n" +
            "     \"text\": true,\n" +
            "     \"image\": true\n" +
            "    },\n" +
            "    \"pageCount\": 248,\n" +
            "    \"printType\": \"BOOK\",\n" +
            "    \"categories\": [\n" +
            "     \"Computers\"\n" +
            "    ],\n" +
            "    \"maturityRating\": \"NOT_MATURE\",\n" +
            "    \"allowAnonLogging\": true,\n" +
            "    \"contentVersion\": \"1.1.1.0.preview.3\",\n" +
            "    \"imageLinks\": {\n" +
            "     \"smallThumbnail\": \"http://books.google.com/books/content?id=IEk2m00o9_IC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api\",\n" +
            "     \"thumbnail\": \"http://books.google.com/books/content?id=IEk2m00o9_IC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api\"\n" +
            "    },\n" +
            "    \"language\": \"en\",\n" +
            "    \"previewLink\": \"http://books.google.ca/books?id=IEk2m00o9_IC&printsec=frontcover&dq=android&hl=&cd=1&source=gbs_api\",\n" +
            "    \"infoLink\": \"http://books.google.ca/books?id=IEk2m00o9_IC&dq=android&hl=&source=gbs_api\",\n" +
            "    \"canonicalVolumeLink\": \"http://books.google.ca/books/about/Android_Apps_Security.html?hl=&id=IEk2m00o9_IC\"\n" +
            "   },\n" +
            "   \"saleInfo\": {\n" +
            "    \"country\": \"CA\",\n" +
            "    \"saleability\": \"NOT_FOR_SALE\",\n" +
            "    \"isEbook\": false\n" +
            "   },\n" +
            "   \"accessInfo\": {\n" +
            "    \"country\": \"CA\",\n" +
            "    \"viewability\": \"PARTIAL\",\n" +
            "    \"embeddable\": true,\n" +
            "    \"publicDomain\": false,\n" +
            "    \"textToSpeechPermission\": \"ALLOWED\",\n" +
            "    \"epub\": {\n" +
            "     \"isAvailable\": true,\n" +
            "     \"acsTokenLink\": \"http://books.google.ca/books/download/Android_Apps_Security-sample-epub.acsm?id=IEk2m00o9_IC&format=epub&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api\"\n" +
            "    },\n" +
            "    \"pdf\": {\n" +
            "     \"isAvailable\": true,\n" +
            "     \"acsTokenLink\": \"http://books.google.ca/books/download/Android_Apps_Security-sample-pdf.acsm?id=IEk2m00o9_IC&format=pdf&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api\"\n" +
            "    },\n" +
            "    \"webReaderLink\": \"http://books.google.ca/books/reader?id=IEk2m00o9_IC&hl=&printsec=frontcover&output=reader&source=gbs_api\",\n" +
            "    \"accessViewStatus\": \"SAMPLE\",\n" +
            "    \"quoteSharingAllowed\": false\n" +
            "   },\n" +
            "   \"searchInfo\": {\n" +
            "    \"textSnippet\": \"This book will provide developers with the information they need to design useful, high-performing, and secure apps that expose end-users to as little risk as possible. Overview of Android OS versions, features, architecture and security.\"\n" +
            "   }\n" +
            "  }\n" +
            " ]\n" +
            "}";
    private BookUtils() {
    }

    public static ArrayList<Books>extractBooks(){
        ArrayList<Books> books = new ArrayList<>();

        // Try to parse the SAMPLE_JSON_RESPONSE. If there's a problem with the way the JSON
        // is formatted, a JSONException exception object will be thrown.
        // Catch the exception so the app doesn't crash, and print the error message to the logs.
        try {

            JSONObject jsonResponse = new JSONObject(SAMPLE_JSON_RESPONSE);
            JSONArray booksArray = jsonResponse.getJSONArray("items");

            for(int i = 0; i < booksArray.length(); i++){
                JSONObject currentBook = booksArray.getJSONObject(i);
                JSONObject volumeInfo = currentBook.getJSONObject("volumeInfo");
                String title = volumeInfo.getString("title");
                String authors = volumeInfo.getString("authors");
                String publisher = volumeInfo.getString("publisher");
                String publishdDate = volumeInfo.getString("publishedDate");
                String language = volumeInfo.getString("language");
                String pageCount = volumeInfo.getString("pageCount");
                String printType = volumeInfo.getString("printType");
                String maturityRating = volumeInfo.getString("maturityRating");

                Books book = new Books(title, authors, publisher, publishdDate, language, pageCount, printType, maturityRating);
                books.add(book);
            }


        } catch (JSONException e) {

            Log.e("QueryUtils", "Problem parsing the earthquake JSON results", e);
        }

        // Return the list of earthquakes
        return books;
    }
}

1 个答案:

答案 0 :(得分:0)

问题在于String authors = volumeInfo.getString("authors");

因为作者是一个数组,您需要使用getJSONArray而不是getString,如下所示:

JSONArray authorsArray = volumeInfo.getJSONArray("authors");

这将为您提供作者数组,但由于您在Book bean中有简单的String类型,您需要准备一个字符串,并附加所有作者,如下所示。

BookUtils代码片段来处理作者数组:

for(int i = 0; i < booksArray.length(); i++){

        JSONObject currentBook = booksArray.getJSONObject(i);
        JSONObject volumeInfo = currentBook.getJSONObject("volumeInfo");
        JSONArray authorsArray = volumeInfo.getJSONArray("authors");
        String authors = "";
        for(int i=0; i<authorsArray.length();i++) {
            authors = authors +","+authorsArray.getString(i);
        }

        //set the other strings as is

        Books book = new Books(title, authors, publisher, publishdDate, language, pageCount, printType, maturityRating);
        books.add(book);
    }