【问题标题】:How to get Java Object from Json returned by Google Custom Api search如何从 Google 自定义 Api 搜索返回的 Json 中获取 Java 对象
【发布时间】:2015-11-19 11:31:12
【问题描述】:

我有以下代码通过谷歌自定义 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 对象。请帮帮我。

【问题讨论】:

  • 我尝试了您的完整网址并得到错误代码 json:googleapis.com/customsearch/…
  • System.out.println(result); 行是什么在“searchAndSaveGoogleCustomSearch()”方法中打印出来?
  • GoogleCustomApiResult类中items的类型是否等于List&lt;GoogleCustomApiResult&gt;而不是List&lt;CustomApiResult &gt;??
  • System.out.println(result) 打印以下内容:GoogleCustomApiResult [title=null, link=null, sn-p=null, cacheId=null, formattedUrl=null, htmlFormattedUrl=null]跨度>
  • 现在试试这个网址,它会正常工作的

标签: java json google-custom-search


【解决方案1】:

查看您的回复,您没有映射与模型 GoogleCustomApiResult 完全相同的 json 结构,因为缺少很多字段。

你有两个选择:

  1. 准确映射 json 结构(不要尝试这样做,因为您有一个巨大的 json!)

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

看看 Gson API 中的JsonParser

同时纠正@Maraboc 指出的模型类中的错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多