如何从Google Custom Api搜索返回Json的Java Object

时间:2015-11-19 11:31:13

标签: java json google-custom-search

我有以下用于通过google custom api检索网页搜索结果的代码

package google.custom.api.results.google.custom.api;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import com.google.gson.Gson;

public class handler {


    public static boolean searchAndSaveGoogleCustomSearch() throws  UnsupportedEncodingException 
    {
        String apiKey="AIzaSyB21aUCd8HYMsHgo7APH-98ah-8tLgkPFM";
        String cxId="005621018181405156379:yvdukowvdte";

        String keyToSearch="News";


        String urlToSearch="https://www.googleapis.com/customsearch/v1?key=" +apiKey+ "&cx="+cxId
                +"&alt=json"+"&q="+keyToSearch;


        try {
            URL url=new URL(urlToSearch);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
              conn.setRequestMethod("GET");
              conn.setRequestProperty("Accept", "application/json");
              BufferedReader br = new BufferedReader(new InputStreamReader ( ( conn.getInputStream() ) ) );
              GoogleCustomApiResult result = new Gson().fromJson(br, GoogleCustomApiResult.class);
              System.out.println(result);
              conn.disconnect();


        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return true;
    }


    public static void main(String[] args) throws UnsupportedEncodingException {

            searchAndSaveGoogleCustomSearch();
            System.out.println("Google Crawl done.");
    }
}

以下是我一直试图从json结果中检索java对象的方法

package google.custom.api.results.google.custom.api;

import java.util.List;

public class GoogleCustomApiResult 
{

      private String link;
      private String htmlFormattedUrl;

      private List<GoogleCustomApiResult> items;

      public String getLink() {
        return link;
      }

      public String getUrl() {
        return htmlFormattedUrl;
      }

      public void setUrl(String htmlFormattedUrl) {
        this.htmlFormattedUrl = htmlFormattedUrl;
      }

      public List<GoogleCustomApiResult> getItems() {
        return items;
      }

      public void setLink(String link) {
        this.link = link;
      }

      public void setGroups(List<GoogleCustomApiResult> items) {
        this.items = items;
      }

      public void getThing (int i) {
        System.out.println(items.get(i));
      }

      public String getLink(int i) {
        return items.get(i).toString();
      }

      public String toString() {
        return String.format("%s", link);
      }  
}

并且还使用这个类

package com.til.et.mynewsletter.core.parser.json.google;

import java.util.List;

public class CustomApiResult 
{
    private String kind;
    private String title;
    private String htmlTitle;
    private String link;
    private String displayLink;
    private String snippet;
    private String htmlSnippet;
    private String cacheId;
    private String formattedUrl;
    private String htmlFormattedUrl;
    //private String htmlSnippet;


    public String getKind() {
        return kind;
    }
    public void setKind(String kind) {
        this.kind = kind;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getHtmlTitle() {
        return htmlTitle;
    }
    public void setHtmlTitle(String htmlTitle) {
        this.htmlTitle = htmlTitle;
    }
    public String getLink() {
        return link;
    }
    public void setLink(String link) {
        this.link = link;
    }
    public String getDisplayLink() {
        return displayLink;
    }
    public void setDisplayLink(String displayLink) {
        this.displayLink = displayLink;
    }
    public String getSnippet() {
        return snippet;
    }
    public void setSnippet(String snippet) {
        this.snippet = snippet;
    }
    public String getHtmlSnippet() {
        return htmlSnippet;
    }
    public void setHtmlSnippet(String htmlSnippet) {
        this.htmlSnippet = htmlSnippet;
    }
    public String getCacheId() {
        return cacheId;
    }
    public void setCacheId(String cacheId) {
        this.cacheId = cacheId;
    }
    public String getFormattedUrl() {
        return formattedUrl;
    }
    public void setFormattedUrl(String formattedUrl) {
        this.formattedUrl = formattedUrl;
    }
    public String getHtmlFormattedUrl() {
        return htmlFormattedUrl;
    }
    public void setHtmlFormattedUrl(String htmlFormattedUrl) {
        this.htmlFormattedUrl = htmlFormattedUrl;
    }
    @Override
    public String toString() {
        return "GoogleCustomApiResult [title=" + title + ", link=" + link + ", snippet=" + snippet + ", cacheId="
                + cacheId + ", formattedUrl=" + formattedUrl + ", htmlFormattedUrl=" + htmlFormattedUrl + "]";
    }

但每次返回的java对象都为null。我是Json的新手,不知道如何解析结果以获取用值填充的java对象。 Url返回结果但值不会进入java对象。请帮帮我。

1 个答案:

答案 0 :(得分:0)

查看您的回答,您没有使用模型GoogleCustomApiResult映射完全相同的json结构,导致许多字段丢失。

您有两种选择:

  1. 映射完全json结构(不要试图这样做,因为你有一个巨大的json!)

  2. 解析您的回复以获取您想要的对象列表(推荐)。

  3. 在Gson API中查看JsonParser

    同样纠正@Maraboc指向的模型类中的错误。