如何使用gson反序列化多个嵌套对象中的多个值?

时间:2019-04-20 09:59:54

标签: android json gson deserialization json-deserialization

我有JSON响应,并且我对来自以下内容的值感兴趣:volumeInfo:标题,作者,缩略图,语言,infoLink;并来自saleInfo:可销售性,金额,货币代码(首先来自retailPrice,如果不存在,则来自listPrice)。 当我尝试反序列化时,它给我空值。

这是JSON响应:

{
 "kind": "books#volumes",
 "totalItems": 612,
 "items": [
  {
   "kind": "books#volume",
   "id": "SiLEmmyNmvkC",
   "etag": "PfYqQ4VVzwY",
   "selfLink": "https://www.googleapis.com/books/v1/volumes/SiLEmmyNmvkC",
   "volumeInfo": {
    "title": "The Art of Resin Clay",
    "subtitle": "Techniques and Projects for Creating Jewelry and Decorative Objects",
    "authors": [
     "Sherri Haab",
     "Rachel Haab",
     "Michelle Haab"
    ],
    "publisher": "Potter Craft",
    "publishedDate": "2012-01-17",
    "description": "Discover the Creative Possibilities of Resin Clay.",
    "industryIdentifiers": [
     {
      "type": "ISBN_13",
      "identifier": "9780823027248"
     },
     {
      "type": "ISBN_10",
      "identifier": "0823027244"
     }
    ],
    "readingModes": {
     "text": true,
     "image": false
    },
    "pageCount": 144,
    "printType": "BOOK",
    "categories": [
     "Crafts & Hobbies"
    ],
    "maturityRating": "NOT_MATURE",
    "allowAnonLogging": true,
    "contentVersion": "0.1.0.0.preview.2",
    "panelizationSummary": {
     "containsEpubBubbles": false,
     "containsImageBubbles": false
    },
    "imageLinks": {
     "smallThumbnail": "http://books.google.com/books/content?id=SiLEmmyNmvkC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api",
     "thumbnail": "http://books.google.com/books/content?id=SiLEmmyNmvkC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
    },
    "language": "en",
    "previewLink": "http://books.google.pl/books?id=SiLEmmyNmvkC&printsec=frontcover&dq=art&hl=&cd=1&source=gbs_api",
    "infoLink": "https://play.google.com/store/books/details?id=SiLEmmyNmvkC&source=gbs_api",
    "canonicalVolumeLink": "https://market.android.com/details?id=book-SiLEmmyNmvkC"
   },
   "saleInfo": {
    "country": "PL",
    "saleability": "FOR_SALE",
    "isEbook": true,
    "listPrice": {
     "amount": 94.35,
     "currencyCode": "PLN"
    },
    "retailPrice": {
     "amount": 66.04,
     "currencyCode": "PLN"
    },
    "buyLink": "https://play.google.com/store/books/details?id=SiLEmmyNmvkC&rdid=book-SiLEmmyNmvkC&rdot=1&source=gbs_api",
    "offers": [
     {
      "finskyOfferType": 1,
      "listPrice": {
       "amountInMicros": 9.435E7,
       "currencyCode": "PLN"
      },
      "retailPrice": {
       "amountInMicros": 6.604E7,
       "currencyCode": "PLN"
      }
     }
    ]
   },
   "accessInfo": {
    "country": "PL",
    "viewability": "PARTIAL",
    "embeddable": true,
    "publicDomain": false,
    "textToSpeechPermission": "ALLOWED_FOR_ACCESSIBILITY",
    "epub": {
     "isAvailable": true,
     "acsTokenLink": "http://books.google.pl/books/download/The_Art_of_Resin_Clay-sample-epub.acsm?id=SiLEmmyNmvkC&format=epub&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api"
    },
    "pdf": {
     "isAvailable": false
    },
    "webReaderLink": "http://play.google.com/books/reader?id=SiLEmmyNmvkC&hl=&printsec=frontcover&source=gbs_api",
    "accessViewStatus": "SAMPLE",
    "quoteSharingAllowed": false
   },
   "searchInfo": {
    "textSnippet": "The Art of Resin Clay explores the creative potential of this material."
   }
  }
 ]
}

这是一个数据类:

public class Book {

    private VolumeInfo mVolumeInfo;
    private SaleInfo mSaleInfo;

    public Book(VolumeInfo volumeInfo, SaleInfo saleInfo) {
        mVolumeInfo = volumeInfo;
        mSaleInfo = saleInfo;
    }

    public class VolumeInfo {
        @SerializedName("title")
        private String mTitle;
        @SerializedName("authors")
        private String[] mAuthors;
        @SerializedName("imageLinks")
        private ImageLinks mImageLinks;
        @SerializedName("language")
        private String mLanguage;
        @SerializedName("infoLink")
        private String mInfoLink;

        public VolumeInfo(String title, String[] authors,ImageLinks imageLinks,String language,String infoLink) {
            this.mTitle = title;
            this.mAuthors = authors;
            this.mImageLinks = imageLinks;
            this.mLanguage = language;
            this.mInfoLink = infoLink;
        }

        public String getTitle() {
            return mTitle;
        }

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

        public String getLanguage() {
            return mLanguage;
        }

        public String getInfoLink() {
            return mInfoLink;
        }

        public class ImageLinks {
            @SerializedName(value = "thumbnail", alternate = "smallThumbnail")
            private String mThumbnail;

            public ImageLinks(String thumbnail) {
                mThumbnail = thumbnail;
            }

            public String getThumbnail() {
                return mThumbnail;
            }
        }
    }

    public class SaleInfo {
        @SerializedName("saleability")
        private String mSaleability;

        public SaleInfo(String saleability) {
            mSaleability = saleability;
        }

        public class Price {
            @SerializedName("amount")
            private String mAmount;
            @SerializedName("currencyCode")
            private String mCurrencyCode;

            public Price(String amount, String currencyCode) {
                mAmount = amount;
                mCurrencyCode = currencyCode;
            }
        }
    }

}

这就是我反序列化JSON(此处使用Volley)的方式:

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,url,null,new Response.Listener<JSONObject>() {
         @Override
         public void onResponse(JSONObject response) {
           if (response != null) {
              try {
                JSONArray jsonItemsArray = response.getJSONArray("items");
                for (int i = 0; i < jsonItemsArray.length(); i++) {  
                  JSONObject item = jsonItemsArray.getJSONObject(i);
                  GsonBuilder gsonBuilder = new GsonBuilder();
                  Gson gson = gsonBuilder.create();
                  List<Book> mBookList = new ArrayList<>();  
                  mBookList.add(gson.fromJson(item.toString(),Book.class));                         
                }
              } catch (JSONException e) {
               e.printStackTrace();
              }
            }
         }
},new Response.ErrorListener() {
     @Override
     public void onErrorResponse(VolleyError error) {
        error.printStackTrace();
     }
});
requestQueue.add(jsonObjectRequest);

我不知道为什么它只给我空值。如果必须创建自己的解串器,它的外观如何?

0 个答案:

没有答案