如何使用GSON获取/解析JSONObject数据

时间:2016-10-19 05:19:19

标签: android gson retrofit retrofit2

我正在尝试将retrofitandroid一起使用,这有点迫使我使用gson

我正在尝试从代码中的payload["response"]["docs"][0]["web_url"]获取数据。

问题:来自getResponse()级以下的密钥model总是给我{}。什么是在Android中处理这个问题的正确方法?另请注意,getCopyright()& getStatus()工作正常。

我也提供样本有效载荷。

我有model这样的课程:

public class ArticleSearchResponseModel {

    @SerializedName("status") private String status;
    @SerializedName("copyright") private String copyright;
    @SerializedName("response") private JSONObject response;

    public String getStatus() {
        return status;
    }

    public String getCopyright() {
        return copyright;
    }

    public JSONObject getResponse() {
        return response;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public void setCopyright(String copyright) {
        this.copyright = copyright;
    }

    public void setResponse(JSONObject response) {
        this.response = response;
    }

}

我的有效负载:

{
  "response": {
    "meta": {
      "hits": 15987906,
      "time": 108,
      "offset": 0
    },
    "docs": [
      {
        "web_url": "http://www.nytimes.com/2016/11/13/insider/gender-issues-in-sharp-focus-at-the-times.html",
        "snippet": "Susan Chira, senior correspondent for gender issues, and Susan Dominus, a Times Magazine writer, talk about men, women and coverage of their changing roles.",
        "lead_paragraph": "Susan Chira, senior correspondent for gender issues, and Susan Dominus, a Times Magazine writer, talk about men, women and coverage of their changing roles.",
        "abstract": null,
        "print_page": null,
        "blog": [],
        "source": "The New York Times",
        "multimedia": [
          {
            "width": 190,
            "url": "images/2016/10/14/insider/14-Insider-SUSANIMAGE/14-Insider-SUSANIMAGE-thumbWide.jpg",
            "height": 126,
            "subtype": "wide",
            "legacy": {
              "wide": "images/2016/10/14/insider/14-Insider-SUSANIMAGE/14-Insider-SUSANIMAGE-thumbWide.jpg",
              "wideheight": "126",
              "widewidth": "190"
            },
            "type": "image"
          },
          {
            "width": 600,
            "url": "images/2016/10/14/insider/14-Insider-SUSANIMAGE/14-Insider-SUSANIMAGE-articleLarge.jpg",
            "height": 400,
            "subtype": "xlarge",
            "legacy": {
              "xlargewidth": "600",
              "xlarge": "images/2016/10/14/insider/14-Insider-SUSANIMAGE/14-Insider-SUSANIMAGE-articleLarge.jpg",
              "xlargeheight": "400"
            },
            "type": "image"
          },
          {
            "width": 75,
            "url": "images/2016/10/14/insider/14-Insider-SUSANIMAGE/14-Insider-SUSANIMAGE-thumbStandard.jpg",
            "height": 75,
            "subtype": "thumbnail",
            "legacy": {
              "thumbnailheight": "75",
              "thumbnail": "images/2016/10/14/insider/14-Insider-SUSANIMAGE/14-Insider-SUSANIMAGE-thumbStandard.jpg",
              "thumbnailwidth": "75"
            },
            "type": "image"
          }
        ],
        "headline": {
          "main": "Gender Issues in Sharp Focus at The Times",
          "content_kicker": "Insider Podcasts",
          "kicker": "Insider Podcast"
        },
        "keywords": [
          {
            "rank": "1",
            "is_major": "N",
            "name": "subject",
            "value": "Presidential Election of 2016"
          },
          {
            "rank": "2",
            "is_major": "N",
            "name": "subject",
            "value": "Women and Girls"
          },
          {
            "rank": "3",
            "is_major": "N",
            "name": "subject",
            "value": "Gender"
          },
          {
            "rank": "4",
            "is_major": "N",
            "name": "subject",
            "value": "Men and Boys"
          },
          {
            "rank": "5",
            "is_major": "N",
            "name": "persons",
            "value": "Trump, Donald J"
          }
        ],
        "pub_date": "2016-11-13T00:00:00Z",
        "document_type": "article",
        "news_desk": "Insider",
        "section_name": "Times Insider",
        "subsection_name": null,
        "byline": {
          "person": [
            {
              "organization": "",
              "role": "reported",
              "firstname": "Susan",
              "rank": 1,
              "lastname": "LEHMAN"
            }
          ],
          "original": "By SUSAN LEHMAN"
        },
        "type_of_material": "News",
        "_id": "58011d9b253f0a0e44966174",
        "word_count": null,
        "slideshow_credits": null
      },
      {
        "web_url": "http://www.nytimes.com/2016/10/25/realestate/doors-of-manhattan.html",
        "snippet": "Even though they stand between us and the chaos of the city, the borough’s distinctive doors are easy to overlook.",
        "lead_paragraph": "Even though they stand between us and the chaos of the city, the borough’s distinctive doors are easy to overlook.",
        "abstract": null,
        "print_page": null,
        "blog": [],
        "source": "The New York Times",
        "multimedia": [],
        "headline": {
          "main": "Doors of Manhattan",
          "content_kicker": "Voyeur",
          "kicker": "Voyeur"
        },
        "keywords": [
          {
            "rank": "1",
            "is_major": "N",
            "name": "subject",
            "value": "Real Estate and Housing (Residential)"
          },
          {
            "rank": "2",
            "is_major": "N",
            "name": "subject",
            "value": "Architecture"
          },
          {
            "rank": "3",
            "is_major": "N",
            "name": "glocations",
            "value": "Upper West Side (Manhattan, NY)"
          },
          {
            "rank": "4",
            "is_major": "N",
            "name": "glocations",
            "value": "Upper East Side (Manhattan, NY)"
          }
        ],
        "pub_date": "2016-10-25T00:00:00Z",
        "document_type": "article",
        "news_desk": "RealEstate",
        "section_name": "Real Estate",
        "subsection_name": null,
        "byline": {
          "person": [
            {
              "firstname": "Photographs",
              "middlename": "George",
              "lastname": "ETHEREDGE",
              "rank": 1,
              "role": "reported",
              "organization": ""
            }
          ],
          "original": "Photographs by GEORGE ETHEREDGE for THE NEW YORK TIMES"
        },
        "type_of_material": "News",
        "_id": "57e94175253f0a6bb40cbffc",
        "word_count": null,
        "slideshow_credits": null
      },
      {
        "web_url": "http://cooking.nytimes.com/recipes/1018356-celery-toasts",
        "snippet": "This was the first recipe that the chef and writer Gabrielle Hamilton brought to The Times as an Eat columnist for the Sunday magazine in 2016, a snack-tray-sandwich version of a celery-and-fennel salad served at her restaurant, Prune, in the East...",
        "lead_paragraph": "This was the first recipe that the chef and writer Gabrielle Hamilton brought to The Times as an Eat columnist for the Sunday magazine in 2016, a snack-tray-sandwich version of a celery-and-fennel salad served at her restaurant, Prune, in the East Village. It calls for thick, white toasted Pullman bread spread wall to wall with unsalted butter, with slices of blue cheese neatly laid on top, below a mound of shaved celery and thinly sliced scallions dressed in garlic, olive oil, lemon juice and salt, and the whole shebang dusted in ground black pepper before being cut in halves or quarters. \"The ingredients come from the grocery store,\" she wrote in her column. \"These toasts are not expensive or intimidating, but they are outstanding.\"",
        "abstract": null,
        "print_page": null,
        "blog": [],
        "source": "du_recipe",
        "multimedia": [
          {
            "credit": "Davide Luciano for The New York Times. Food stylist: Michelle Gatton. Prop stylist: Alex Brannian.",
            "url": "images/2016/10/23/magazine/23eat/23eat-thumbStandard-v2.jpg",
            "rank": "1",
            "height": 75,
            "subtype": "thumbnail",
            "legacy": [],
            "caption": "Celery Toasts",
            "type": "image",
            "width": 75
          },
          {
            "credit": "Davide Luciano for The New York Times. Food stylist: Michelle Gatton. Prop stylist: Alex Brannian.",
            "url": "images/2016/10/23/magazine/23eat/23mag-23eat-t_CA1-articleLarge.jpg",
            "rank": "1",
            "height": 400,
            "subtype": "large",
            "legacy": [],
            "caption": "Celery Toasts",
            "type": "image",
            "width": 600
          }
        ],
        "headline": {
          "main": "A Snack Tray to Gather the Family Around",
          "name": "Celery Toasts"
        },
        "keywords": [],
        "pub_date": "2016-10-23T00:00:00Z",
        "document_type": "recipe",
        "news_desk": null,
        "section_name": null,
        "subsection_name": null,
        "byline": {
          "person": [
            {
              "organization": "",
              "role": "reported",
              "firstname": "Gabrielle",
              "rank": 1,
              "lastname": "Hamilton"
            }
          ],
          "original": "Gabrielle Hamilton"
        },
        "type_of_material": "Recipe",
        "_id": "580696f1253f0a7d028b0864",
        "word_count": "101",
        "slideshow_credits": null
      },
      {
        "web_url": "http://www.nytimes.com/2016/10/23/books/review/the-story-behind-this-weeks-best-sellers.html",
        "snippet": "Ruth Bader Ginsburg, whose anthology “My Own Words” is No. 12 in hardcover nonfiction, has something in common with Notorious B.I.G.",
        "lead_paragraph": "Ruth Bader Ginsburg, whose anthology “My Own Words” is No. 12 in hardcover nonfiction, has something in common with Notorious B.I.G.",
        "abstract": null,
        "print_page": "30",
        "blog": [],
        "source": "The New York Times",
        "multimedia": [
          {
            "width": 190,
            "url": "images/2016/10/23/books/review/23inside-list/23inside-list-thumbWide.jpg",
            "height": 126,
            "subtype": "wide",
            "legacy": {
              "wide": "images/2016/10/23/books/review/23inside-list/23inside-list-thumbWide.jpg",
              "wideheight": "126",
              "widewidth": "190"
            },
            "type": "image"
          },
          {
            "width": 75,
            "url": "images/2016/10/23/books/review/23inside-list/23inside-list-thumbStandard.jpg",
            "height": 75,
            "subtype": "thumbnail",
            "legacy": {
              "thumbnailheight": "75",
              "thumbnail": "images/2016/10/23/books/review/23inside-list/23inside-list-thumbStandard.jpg",
              "thumbnailwidth": "75"
            },
            "type": "image"
          }
        ],
        "headline": {
          "main": "The Story Behind This Week’s Best Sellers"
        },
        "keywords": [
          {
            "rank": "1",
            "is_major": "N",
            "name": "subject",
            "value": "Books and Literature"
          },
          {
            "rank": "2",
            "is_major": "N",
            "name": "persons",
            "value": "Ginsburg, Ruth Bader"
          }
        ],
        "pub_date": "2016-10-23T00:00:00Z",
        "document_type": "article",
        "news_desk": "BookReview",
        "section_name": "Books",
        "subsection_name": "Book Review",
        "byline": {
          "person": [
            {
              "organization": "",
              "role": "reported",
              "firstname": "Gregory",
              "rank": 1,
              "lastname": "COWLES"
            }
          ],
          "original": "By GREGORY COWLES"
        },
        "type_of_material": "News",
        "_id": "5800f337253f0a7985625011",
        "word_count": null,
        "slideshow_credits": null
      },
      {
        "web_url": "http://www.nytimes.com/2016/10/23/books/review/ngugi-wa-thiongo-birth-of-a-dream-weaver.html",
        "snippet": "A Kenyan considers his early years as a student and writer.",
        "lead_paragraph": "A Kenyan considers his early years as a student and writer.",
        "abstract": null,
        "print_page": "25",
        "blog": [],
        "source": "The New York Times",
        "multimedia": [
          {
            "width": 190,
            "url": "images/2016/10/23/books/review/23Wrong/23Wrong-thumbWide.jpg",
            "height": 126,
            "subtype": "wide",
            "legacy": {
              "wide": "images/2016/10/23/books/review/23Wrong/23Wrong-thumbWide.jpg",
              "wideheight": "126",
              "widewidth": "190"
            },
            "type": "image"
          },
          {
            "width": 600,
            "url": "images/2016/10/23/books/review/23Wrong/23Wrong-articleLarge.jpg",
            "height": 400,
            "subtype": "xlarge",
            "legacy": {
              "xlargewidth": "600",
              "xlarge": "images/2016/10/23/books/review/23Wrong/23Wrong-articleLarge.jpg",
              "xlargeheight": "400"
            },
            "type": "image"
          },
          {
            "width": 75,
            "url": "images/2016/10/23/books/review/23Wrong/23Wrong-thumbStandard.jpg",
            "height": 75,
            "subtype": "thumbnail",
            "legacy": {
              "thumbnailheight": "75",
              "thumbnail": "images/2016/10/23/books/review/23Wrong/23Wrong-thumbStandard.jpg",
              "thumbnailwidth": "75"
            },
            "type": "image"
          }
        ],
        "headline": {
          "main": "Ngugi wa Thiong’o on Starting Out as a Writer",
          "content_kicker": "Nonfiction",
          "kicker": "Nonfiction",
          "print_headline": "A Long Look Back"
        },
        "keywords": [
          {
            "rank": "2",
            "is_major": "N",
            "name": "persons",
            "value": "Thiong'o, Ngugi wa"
          },
          {
            "rank": "3",
            "is_major": "N",
            "name": "subject",
            "value": "Books and Literature"
          },
          {
            "rank": "4",
            "is_major": "N",
            "name": "subject",
            "value": "Writing and Writers"
          }
        ],
        "pub_date": "2016-10-23T00:00:00Z",
        "document_type": "article",
        "news_desk": "BookReview",
        "section_name": "Books",
        "subsection_name": "Book Review",
        "byline": {
          "person": [
            {
              "organization": "",
              "role": "reported",
              "firstname": "Michela",
              "rank": 1,
              "lastname": "WRONG"
            }
          ],
          "original": "By MICHELA WRONG"
        },
        "type_of_material": "Review",
        "_id": "57ff4d1d253f0a6b9720abd2",
        "word_count": null,
        "slideshow_credits": null
      },
      {
        "web_url": "http://cooking.nytimes.com/recipes/1018347-lemon-drizzle-cake",
        "snippet": "This light and moist lemon poundcake has a crunchy sugar glaze that crystallizes on top, giving a contrasting texture to the soft crumb underneath. It’s an easy-to-make, crowd-pleasing cake that’s excellent on its own but takes well to...",
        "lead_paragraph": "This light and moist lemon poundcake has a crunchy sugar glaze that crystallizes on top, giving a contrasting texture to the soft crumb underneath. It’s an easy-to-make, crowd-pleasing cake that’s excellent on its own but takes well to embellishments. A scoop of ice cream or sorbet, fruit compote and-or lemon curd are all wonderful alongside.",
        "abstract": null,
        "print_page": null,
        "blog": [],
        "source": "du_recipe",
        "multimedia": [
          {
            "credit": "Andrew Scrivani for The New York Times",
            "url": "images/2016/10/19/dining/19BAKEOFF2/19BAKEOFF2-thumbStandard.jpg",
            "rank": "1",
            "height": 75,
            "subtype": "thumbnail",
            "legacy": [],
            "type": "image",
            "width": 75
          },
          {
            "credit": "Andrew Scrivani for The New York Times",
            "url": "images/2016/10/19/dining/19BAKEOFF2/19BAKEOFF2-articleLarge.jpg",
            "rank": "1",
            "height": 400,
            "subtype": "large",
            "legacy": [],
            "type": "image",
            "width": 600
          }
        ],
        "headline": {
          "main": "‘The Great British Bake Off’ Changes the Way the British Bake",
          "name": "Lemon Drizzle Cake"
        },
        "keywords": [],
        "pub_date": "2016-10-19T00:00:00Z",
        "document_type": "recipe",
        "news_desk": null,
        "section_name": null,
        "subsection_name": null,
        "byline": {
          "person": [
            {
              "organization": "",
              "role": "reported",
              "firstname": "Melissa",
              "rank": 1,
              "lastname": "Clark"
            }
          ],
          "original": "Melissa Clark"
        },
        "type_of_material": "Recipe",
        "_id": "58066d7c253f0a7d028b07d0",
        "word_count": "250",
        "slideshow_credits": null
      }
    ]
  },
  "status": "OK",
  "copyright": "Copyright (c) 2013 The New York Times Company.  All Rights Reserved."
}

3 个答案:

答案 0 :(得分:3)

在开始之前,我不熟悉改造。 如果你想将json序列化/反序列化为pojo,你最好制作pojo对象。

class Response {
    Meta meta;
    List<Docs> docs;
}

class Docs {
    String webUrl;
    Mutimedia multimedia;
    ... 
}

问题the key getResponse(), from below model class, always gives me {}发生是因为gson无法确定将json转换为普通旧java对象的正确对象。

答案 1 :(得分:1)

为了使您的Response模型类使用http://www.jsonschema2pojo.org/

Making POJO simple

答案 2 :(得分:1)

你不需要在模型中制作精确的结构 你可以继续使用你的代码只需要很小的改变

使用

@SerializedName("response") private JsonObject response;

而不是

@SerializedName("response") private JSONObject response;

并在导入

import com.google.gson.JsonObject;