给定GoogleBooks API的模型类

时间:2016-07-05 12:14:07

标签: java android json google-books

我是Android新手,我正在创建一个应用程序来学习JSON解析。我想为我的应用解析Google Books API的JSON数据,但是我在创建API的Model类时遇到了问题。以下是数据中显示的第一个结果的JSON数据:

    {

    "kind": "books#volumes",
    "totalItems": 1591,
    "items": [
        {
            "kind": "books#volume",
            "id": "An4_e3Cr3zAC",
            "etag": "DWmqBRkB8dw",
            "selfLink": "https://www.googleapis.com/books/v1/volumes/An4_e3Cr3zAC",
            "volumeInfo": {
                "title": "The Rules of the Game",
                "authors": [
                    "Neil Strauss"
                ],
                "publisher": "Canongate Books",
                "publishedDate": "2011-09-29",
                "description": "If you want to play The Game you need to know The Rules This book is not a story. It is a how-to book. This Stylelife Challenge is not meant to be read. It is meant to be performed. Whatever experience level you have, whatever strengths and weaknesses you may have, whether you're a virgin or a Don Juan, the stage has been set for you to perform at your highest capacity. The Stylelife Challenge is a simple, easy-to-follow guide to the basics of approaching and attracting women. The Challenge is simply what works best and fastest. Neil Strauss spent four years gathering this knowledge, living it and sharing it. He's tested the specific material in this book on over 13,000 men of varying ages, nationalities and backgrounds. Part practical application and part sequel, this is the further adventures of Style and his game techniques. The result: A month-long workout program for your social, attraction, dating and seduction skills.",
                "industryIdentifiers": [
                    {
                        "type": "ISBN_13",
                        "identifier": "9781847673558"
                    },
                    {
                        "type": "ISBN_10",
                        "identifier": "1847673554"
                    }
                ],
                "readingModes": {
                    "text": true,
                    "image": true
                },
                "pageCount": 352,
                "printType": "BOOK",
                "categories": [
                    "Biography & Autobiography"
                ],
                "averageRating": 3.5,
                "ratingsCount": 82,
                "maturityRating": "NOT_MATURE",
                "allowAnonLogging": true,
                "contentVersion": "1.7.6.0.preview.3",
                "imageLinks": {
                    "smallThumbnail": "http://books.google.co.in/books/content?id=An4_e3Cr3zAC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api",
                    "thumbnail": "http://books.google.co.in/books/content?id=An4_e3Cr3zAC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
                },
                "language": "en",
                "previewLink": "http://books.google.co.in/books?id=An4_e3Cr3zAC&printsec=frontcover&dq=game&hl=&cd=1&source=gbs_api",
                "infoLink": "http://books.google.co.in/books?id=An4_e3Cr3zAC&dq=game&hl=&source=gbs_api",
                "canonicalVolumeLink": "http://books.google.co.in/books/about/The_Rules_of_the_Game.html?hl=&id=An4_e3Cr3zAC"
            },
            "saleInfo": {
                "country": "IN",
                "saleability": "FOR_SALE",
                "isEbook": true,
                "listPrice": {
                    "amount": 399.0,
                    "currencyCode": "INR"
                },
                "retailPrice": {
                    "amount": 279.3,
                    "currencyCode": "INR"
                },
                "buyLink": "http://books.google.co.in/books?id=An4_e3Cr3zAC&dq=game&hl=&buy=&source=gbs_api",
                "offers": [
                    {
                        "finskyOfferType": 1,
                        "listPrice": {
                            "amountInMicros": 3.99E8,
                            "currencyCode": "INR"
                        },
                        "retailPrice": {
                            "amountInMicros": 2.793E8,
                            "currencyCode": "INR"
                        }
                    }
                ]
            },
            "accessInfo": {
                "country": "IN",
                "viewability": "PARTIAL",
                "embeddable": true,
                "publicDomain": false,
                "textToSpeechPermission": "ALLOWED",
                "epub": {
                    "isAvailable": true,
                    "acsTokenLink": "http://books.google.co.in/books/download/The_Rules_of_the_Game-sample-epub.acsm?id=An4_e3Cr3zAC&format=epub&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api"
                },
                "pdf": {
                    "isAvailable": true,
                    "acsTokenLink": "http://books.google.co.in/books/download/The_Rules_of_the_Game-sample-pdf.acsm?id=An4_e3Cr3zAC&format=pdf&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api"
                },
                "webReaderLink": "http://books.google.co.in/books/reader?id=An4_e3Cr3zAC&hl=&printsec=frontcover&output=reader&source=gbs_api",
                "accessViewStatus": "SAMPLE",
                "quoteSharingAllowed": false
            },
            "searchInfo": {
                "textSnippet": "He's tested the specific material in this book on over 13,000 men of varying ages, nationalities and backgrounds. Part practical application and part sequel, this is the further adventures of Style and his game techniques."
            }
        }
    ]
}

我创建了四个Model类(我认为合适)。这是所有四个类的代码。所有类都包含各自的setter和getter。

public class BookItems {

String kind;
String id;
String etag;
String selfLink;
}

public class BookVolumeInfo {

String title;

String publisher;
String publishedDate;
String description;

long pageCount;

float averageRating;
long ratingsCount;
String maturityRating;
}

public class BookAuthors {

String authors;
}

public class BookCategories {

String categories;
}

如果可能,我想在一个班级中完成所有这些。当我运行代码时,我没有得到这本书的标题。这是我项目的主要代码。

    public class MainActivity extends AppCompatActivity {

    public static final String Logcat = "vmech";

    Button searchButton;
    EditText editTextSearch;
    TextView textViewDisplayResult;
    String newText;
    String urlstring;

    public static final String MyAPIKey =  "Your_Api_Key";

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

        searchButton = (Button) findViewById(R.id.buttonSerch);
        editTextSearch = (EditText) findViewById(R.id.editTextSearch);
        textViewDisplayResult = (TextView) findViewById(R.id.textViewDisplayResult);

        searchButton.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                newText = editTextSearch.getText().toString();
                if(newText.length()>0){
                    newText = newText.replace(" ", "+");
                    urlstring = "https://www.googleapis.com/books/v1/volumes?q=";
                    urlstring = urlstring + newText + "&maxResults=5" + "&key=" + MyAPIKey;
//                    Log.e(Logcat,"URL created successfully");
//                    Log.i(Logcat,"URL created successfully");
                }
                else {
                    Toast.makeText(MainActivity.this, "Please enter a book name to search.", Toast.LENGTH_LONG).show();
//                    Log.e(Logcat,"Search field empty");
//                    Log.i(Logcat,"Search field empty");
                }
                new JSONTask().execute(urlstring);
                //Toast.makeText(MainActivity.this, "Search Button Clicked.", Toast.LENGTH_LONG).show();

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        //super.onCreateOptionsMenu(menu);
        MenuInflater inflater=getMenuInflater();
        inflater.inflate(R.menu.menu_main, menu);
        return true;

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        Toast.makeText(this, "This is the Settings item", Toast.LENGTH_LONG).show();
        return true;

    }

    public class JSONTask extends AsyncTask<String, String, List<BookVolumeInfo>>{

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected List<BookVolumeInfo> doInBackground(String... params) {
            HttpURLConnection connection = null;
            BufferedReader bufferedReader = null;

//            URL url = null;
            try {
                URL url = new URL(urlstring);

                connection = (HttpURLConnection) url.openConnection();
                connection.connect();

                InputStream inputstream = connection.getInputStream();
                bufferedReader = new BufferedReader(new InputStreamReader(inputstream));

                StringBuffer stringbuffer = new StringBuffer();

                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    stringbuffer.append(line);
                }

                String finalJson = stringbuffer.toString();

                JSONObject parentObject = new JSONObject(finalJson);
                JSONArray parentArray = parentObject.getJSONArray("items");

                List<BookVolumeInfo> bookVolumeInfoList = new ArrayList<>();

                for(int i=0; i<parentArray.length(); i++){
                    JSONObject finalObject = parentArray.getJSONObject(i);

                    BookVolumeInfo bookVolumeInfo = new BookVolumeInfo();
                    BookAuthors bookAuthors = new BookAuthors();
                    BookCategories bookCategories = new BookCategories();
                    bookVolumeInfo.setTitle(finalObject.getString("title"));
                    bookVolumeInfo.setDescription(finalObject.getString("description"));
                    bookVolumeInfo.setAverageRating((float) finalObject.getDouble("averageRating"));
                    bookAuthors.setAuthors(finalObject.getString("authors"));
                    bookCategories.setCategories(finalObject.getString("categories"));

                    bookVolumeInfoList.add(bookVolumeInfo);
                }


                return bookVolumeInfoList;

            } catch (IOException e){
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } finally {
                if (connection != null)
                {
                    connection.disconnect();
                }
                try {
                    if (bufferedReader != null){
                        bufferedReader.close();
                    }
                }catch (IOException e){
                    e.printStackTrace();
                }
            }

            return null;

        }

        @Override
        protected void onPostExecute(List<BookVolumeInfo> result) {
            super.onPostExecute(result);
            textViewDisplayResult.setText((CharSequence) result);
        }
    }

}

当我运行代码时,它没有给出任何错误,但是当我在Android监视器窗口中搜索它时,&#34;标题无法找到&#34;。

请帮忙。

2 个答案:

答案 0 :(得分:0)

here生成模型类

答案 1 :(得分:0)

以下是json主体到java类的完整实现

 public class DemoClass {
    private Items[] items;

    private String totalItems;

    private String kind;

    public Items[] getItems ()
    {
        return items;
    }

    public void setItems (Items[] items)
    {
        this.items = items;
    }

    public String getTotalItems ()
    {
        return totalItems;
    }

    public void setTotalItems (String totalItems)
    {
        this.totalItems = totalItems;
    }

    public String getKind ()
    {
        return kind;
    }

    public void setKind (String kind)
    {
        this.kind = kind;
    }


    public class Items
    {
        private SaleInfo saleInfo;

        private String id;

        private SearchInfo searchInfo;

        private String etag;

        private VolumeInfo volumeInfo;

        private String selfLink;

        private AccessInfo accessInfo;

        private String kind;

        public SaleInfo getSaleInfo ()
        {
            return saleInfo;
        }

        public void setSaleInfo (SaleInfo saleInfo)
        {
            this.saleInfo = saleInfo;
        }

        public String getId ()
        {
            return id;
        }

        public void setId (String id)
        {
            this.id = id;
        }

        public SearchInfo getSearchInfo ()
        {
            return searchInfo;
        }

        public void setSearchInfo (SearchInfo searchInfo)
        {
            this.searchInfo = searchInfo;
        }

        public String getEtag ()
        {
            return etag;
        }

        public void setEtag (String etag)
        {
            this.etag = etag;
        }

        public VolumeInfo getVolumeInfo ()
        {
            return volumeInfo;
        }

        public void setVolumeInfo (VolumeInfo volumeInfo)
        {
            this.volumeInfo = volumeInfo;
        }

        public String getSelfLink ()
        {
            return selfLink;
        }

        public void setSelfLink (String selfLink)
        {
            this.selfLink = selfLink;
        }

        public AccessInfo getAccessInfo ()
        {
            return accessInfo;
        }

        public void setAccessInfo (AccessInfo accessInfo)
        {
            this.accessInfo = accessInfo;
        }

        public String getKind ()
        {
            return kind;
        }

        public void setKind (String kind)
        {
            this.kind = kind;
        }

        public class SearchInfo
        {
            private String textSnippet;

            public String getTextSnippet ()
            {
                return textSnippet;
            }

            public void setTextSnippet (String textSnippet)
            {
                this.textSnippet = textSnippet;
            }
        }

        public class AccessInfo
        {
            private String webReaderLink;

            private String textToSpeechPermission;

            private String publicDomain;

            private String viewability;

            private String accessViewStatus;

            private Pdf pdf;

            private Epub epub;

            private String embeddable;

            private String quoteSharingAllowed;

            private String country;

            public String getWebReaderLink ()
            {
                return webReaderLink;
            }

            public void setWebReaderLink (String webReaderLink)
            {
                this.webReaderLink = webReaderLink;
            }

            public String getTextToSpeechPermission ()
            {
                return textToSpeechPermission;
            }

            public void setTextToSpeechPermission (String textToSpeechPermission)
            {
                this.textToSpeechPermission = textToSpeechPermission;
            }

            public String getPublicDomain ()
            {
                return publicDomain;
            }

            public void setPublicDomain (String publicDomain)
            {
                this.publicDomain = publicDomain;
            }

            public String getViewability ()
            {
                return viewability;
            }

            public void setViewability (String viewability)
            {
                this.viewability = viewability;
            }

            public String getAccessViewStatus ()
            {
                return accessViewStatus;
            }

            public void setAccessViewStatus (String accessViewStatus)
            {
                this.accessViewStatus = accessViewStatus;
            }

            public Pdf getPdf ()
            {
                return pdf;
            }

            public void setPdf (Pdf pdf)
            {
                this.pdf = pdf;
            }

            public Epub getEpub ()
            {
                return epub;
            }

            public void setEpub (Epub epub)
            {
                this.epub = epub;
            }

            public String getEmbeddable ()
            {
                return embeddable;
            }

            public void setEmbeddable (String embeddable)
            {
                this.embeddable = embeddable;
            }

            public String getQuoteSharingAllowed ()
            {
                return quoteSharingAllowed;
            }

            public void setQuoteSharingAllowed (String quoteSharingAllowed)
            {
                this.quoteSharingAllowed = quoteSharingAllowed;
            }

            public String getCountry ()
            {
                return country;
            }

            public void setCountry (String country)
            {
                this.country = country;
            }

            public class Pdf
            {
                private String acsTokenLink;

                private String isAvailable;

                public String getAcsTokenLink ()
                {
                    return acsTokenLink;
                }

                public void setAcsTokenLink (String acsTokenLink)
                {
                    this.acsTokenLink = acsTokenLink;
                }

                public String getIsAvailable ()
                {
                    return isAvailable;
                }

                public void setIsAvailable (String isAvailable)
                {
                    this.isAvailable = isAvailable;
                }
            }

            public class Epub
            {
                private String acsTokenLink;

                private String isAvailable;

                public String getAcsTokenLink ()
                {
                    return acsTokenLink;
                }

                public void setAcsTokenLink (String acsTokenLink)
                {
                    this.acsTokenLink = acsTokenLink;
                }

                public String getIsAvailable ()
                {
                    return isAvailable;
                }

                public void setIsAvailable (String isAvailable)
                {
                    this.isAvailable = isAvailable;
                }
            }
        }

        public class SaleInfo
        {
            private RetailPrice retailPrice;

            private String saleability;

            private ListPrice listPrice;

            private Offers[] offers;

            private String buyLink;

            private String isEbook;

            private String country;

            public RetailPrice getRetailPrice ()
            {
                return retailPrice;
            }

            public void setRetailPrice (RetailPrice retailPrice)
            {
                this.retailPrice = retailPrice;
            }

            public String getSaleability ()
            {
                return saleability;
            }

            public void setSaleability (String saleability)
            {
                this.saleability = saleability;
            }

            public ListPrice getListPrice ()
            {
                return listPrice;
            }

            public void setListPrice (ListPrice listPrice)
            {
                this.listPrice = listPrice;
            }

            public Offers[] getOffers ()
            {
                return offers;
            }

            public void setOffers (Offers[] offers)
            {
                this.offers = offers;
            }

            public String getBuyLink ()
            {
                return buyLink;
            }

            public void setBuyLink (String buyLink)
            {
                this.buyLink = buyLink;
            }

            public String getIsEbook ()
            {
                return isEbook;
            }

            public void setIsEbook (String isEbook)
            {
                this.isEbook = isEbook;
            }

            public String getCountry ()
            {
                return country;
            }

            public void setCountry (String country)
            {
                this.country = country;
            }

            public class Offers
            {
                private RetailPrice retailPrice;

                private ListPrice listPrice;

                private String finskyOfferType;

                public RetailPrice getRetailPrice ()
                {
                    return retailPrice;
                }

                public void setRetailPrice (RetailPrice retailPrice)
                {
                    this.retailPrice = retailPrice;
                }

                public ListPrice getListPrice ()
                {
                    return listPrice;
                }

                public void setListPrice (ListPrice listPrice)
                {
                    this.listPrice = listPrice;
                }

                public String getFinskyOfferType ()
                {
                    return finskyOfferType;
                }

                public void setFinskyOfferType (String finskyOfferType)
                {
                    this.finskyOfferType = finskyOfferType;
                }
            }

            public class RetailPrice
            {
                private String amount;

                private String currencyCode;

                public String getAmount ()
                {
                    return amount;
                }

                public void setAmount (String amount)
                {
                    this.amount = amount;
                }

                public String getCurrencyCode ()
                {
                    return currencyCode;
                }

                public void setCurrencyCode (String currencyCode)
                {
                    this.currencyCode = currencyCode;
                }
            }

            public class ListPrice
            {
                private String amount;

                private String currencyCode;

                public String getAmount ()
                {
                    return amount;
                }

                public void setAmount (String amount)
                {
                    this.amount = amount;
                }

                public String getCurrencyCode ()
                {
                    return currencyCode;
                }

                public void setCurrencyCode (String currencyCode)
                {
                    this.currencyCode = currencyCode;
                }
            }
        }

        public class VolumeInfo
        {
            private String pageCount;

            private String averageRating;

            private ReadingModes readingModes;

            private String infoLink;

            private String printType;

            private String allowAnonLogging;

            private String publisher;

            private String[] authors;

            private String canonicalVolumeLink;

            private String title;

            private String previewLink;

            private String description;

            private String ratingsCount;

            private ImageLinks imageLinks;

            private String contentVersion;

            private String[] categories;

            private String language;

            private String publishedDate;

            private IndustryIdentifiers[] industryIdentifiers;

            private String maturityRating;

            public String getPageCount ()
            {
                return pageCount;
            }

            public void setPageCount (String pageCount)
            {
                this.pageCount = pageCount;
            }

            public String getAverageRating ()
            {
                return averageRating;
            }

            public void setAverageRating (String averageRating)
            {
                this.averageRating = averageRating;
            }

            public ReadingModes getReadingModes ()
            {
                return readingModes;
            }

            public void setReadingModes (ReadingModes readingModes)
            {
                this.readingModes = readingModes;
            }

            public String getInfoLink ()
            {
                return infoLink;
            }

            public void setInfoLink (String infoLink)
            {
                this.infoLink = infoLink;
            }

            public String getPrintType ()
            {
                return printType;
            }

            public void setPrintType (String printType)
            {
                this.printType = printType;
            }

            public String getAllowAnonLogging ()
            {
                return allowAnonLogging;
            }

            public void setAllowAnonLogging (String allowAnonLogging)
            {
                this.allowAnonLogging = allowAnonLogging;
            }

            public String getPublisher ()
            {
                return publisher;
            }

            public void setPublisher (String publisher)
            {
                this.publisher = publisher;
            }

            public String[] getAuthors ()
            {
                return authors;
            }

            public void setAuthors (String[] authors)
            {
                this.authors = authors;
            }

            public String getCanonicalVolumeLink ()
            {
                return canonicalVolumeLink;
            }

            public void setCanonicalVolumeLink (String canonicalVolumeLink)
            {
                this.canonicalVolumeLink = canonicalVolumeLink;
            }

            public String getTitle ()
            {
                return title;
            }

            public void setTitle (String title)
            {
                this.title = title;
            }

            public String getPreviewLink ()
            {
                return previewLink;
            }

            public void setPreviewLink (String previewLink)
            {
                this.previewLink = previewLink;
            }

            public String getDescription ()
            {
                return description;
            }

            public void setDescription (String description)
            {
                this.description = description;
            }

            public String getRatingsCount ()
            {
                return ratingsCount;
            }

            public void setRatingsCount (String ratingsCount)
            {
                this.ratingsCount = ratingsCount;
            }

            public ImageLinks getImageLinks ()
            {
                return imageLinks;
            }

            public void setImageLinks (ImageLinks imageLinks)
            {
                this.imageLinks = imageLinks;
            }

            public String getContentVersion ()
            {
                return contentVersion;
            }

            public void setContentVersion (String contentVersion)
            {
                this.contentVersion = contentVersion;
            }

            public String[] getCategories ()
            {
                return categories;
            }

            public void setCategories (String[] categories)
            {
                this.categories = categories;
            }

            public String getLanguage ()
            {
                return language;
            }

            public void setLanguage (String language)
            {
                this.language = language;
            }

            public String getPublishedDate ()
            {
                return publishedDate;
            }

            public void setPublishedDate (String publishedDate)
            {
                this.publishedDate = publishedDate;
            }

            public IndustryIdentifiers[] getIndustryIdentifiers ()
            {
                return industryIdentifiers;
            }

            public void setIndustryIdentifiers (IndustryIdentifiers[] industryIdentifiers)
            {
                this.industryIdentifiers = industryIdentifiers;
            }

            public String getMaturityRating ()
            {
                return maturityRating;
            }

            public void setMaturityRating (String maturityRating)
            {
                this.maturityRating = maturityRating;
            }

            public class ImageLinks
            {
                private String thumbnail;

                private String smallThumbnail;

                public String getThumbnail ()
                {
                    return thumbnail;
                }

                public void setThumbnail (String thumbnail)
                {
                    this.thumbnail = thumbnail;
                }

                public String getSmallThumbnail ()
                {
                    return smallThumbnail;
                }

                public void setSmallThumbnail (String smallThumbnail)
                {
                    this.smallThumbnail = smallThumbnail;
                }
            }

            public class ReadingModes
            {
                private String text;

                private String image;

                public String getText ()
                {
                    return text;
                }

                public void setText (String text)
                {
                    this.text = text;
                }

                public String getImage ()
                {
                    return image;
                }

                public void setImage (String image)
                {
                    this.image = image;
                }
            }

            public class IndustryIdentifiers
            {
                private String type;

                private String identifier;

                public String getType ()
                {
                    return type;
                }

                public void setType (String type)
                {
                    this.type = type;
                }

                public String getIdentifier ()
                {
                    return identifier;
                }

                public void setIdentifier (String identifier)
                {
                    this.identifier = identifier;
                }
            }
        }
    }
}

你可以使用Gson(https://github.com/google/gson)将json字符串直接转换为java pojo对象,比如

new Gson().fromJson(finalJson,GoogleBook.class);