我有这个 json 作为字符串(这是来自谷歌自定义搜索)。我已经制作了解析它所必需的等效 Java 类。我使用 gson 并得到一个 NullPointerException。
"items": [
{
"kind": "customsearch#result",
"title": "A Florida Road Trip - Articles | Travel + Leisure",
"htmlTitle": "A \u003cb\u003eFlorida\u003c/b\u003e Road Trip - \u003cb\u003eArticles\u003c/b\u003e | Travel + Leisure",
"link": "http://www.travelandleisure.com/articles/paradise-usa",
"displayLink": "www.travelandleisure.com",
"snippet": "On a road trip across Florida, Karrie Jacobs goes in search of the authentic amid New Urbanist experiments in postmodern nostalgia.",
"htmlSnippet": "On a road trip across \u003cb\u003eFlorida\u003c/b\u003e, Karrie Jacobs goes in search of the authentic amid \u003cbr\u003e New Urbanist experiments in postmodern nostalgia.",
"cacheId": "QrfYt6p-U3gJ",
"formattedUrl": "www.travelandleisure.com/articles/paradise-usa",
"htmlFormattedUrl": "www.travelandleisure.com/\u003cb\u003earticles\u003c/b\u003e/paradise-usa",
"pagemap": {
"cse_image": [
{
"src": "http://static0.travelandleisure.com/images/amexpub/0000/6261/200702_urban.jpg"
}
],
"cse_thumbnail": [
{
"width": "160",
"height": "200",
"src": "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcR_Jhmej45Lu7L3bQoKz1poITJ5ZeuVvKhH62myfBOj-1VEX9oqwIhvH74"
}
],
"metatags": [
{
"fb:app_id": "145695458805001",
"og:url": "http://www.travelandleisure.com/articles/paradise-usa",
"og:site_name": "Travel + Leisure",
"og:image": "http://static0.travelandleisure.com/images/amexpub/0000/6261/200702_urban.jpg",
"og:type": "article",
"og:title": "Driving: Florida’s New Urbanist Experiments",
"og:description": "On a road trip across Florida, Karrie Jacobs goes in search of the authentic amid New Urbanist exper..."
}
]
}
}
我等效的java类如下:
public Class Mapper
{
public Items[] items;
}
public Class Items
{
public String title;
public String htmlSnippet;
public String link;
public Pagemap pagemap;
}
public Class Pagemap
{
public Cse_image[] image;
}
public Class Cse_image
{
public String src;
}
public Class Parser
{
public static void main(String[] args)
{
//assume json is the string representation of the above json
Gson gson = new GsonBuilder().create();
Mapper mapper= gson.fromJson(json,Mapper.class);
System.out.println("src here"+mapper.items[0].pagemap.image[0].src);
}
}
上面的代码抛出了一个NullPointerException
,但是如果我打印到页面地图,我会得到一个具有有效哈希码的对象。任何指针?