为json响应创建一个类

时间:2013-04-25 15:19:28

标签: java json

我正在尝试下载从网上下载的代码。这是关于阅读谷歌搜索页面的总搜索结果。

import com.google.gson.Gson;
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLEncoder;


    public class Test {

        public static void main(String[] args) throws Exception {
            String google = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";
            String search = "my";
            String charset = "UTF-8";

            URL url = new URL(google + URLEncoder.encode(search, charset));
            System.out.println(google + URLEncoder.encode(search, charset));
            Reader reader = new InputStreamReader(url.openStream(), charset);
            GoogleResults results = new Gson().fromJson(reader, GoogleResults.class);


            System.out.println(results.getResponseData().getResults().size());

        }
    }

搜索结果

"queries": {
  "nextPage": [
   {
    "title": "Google Custom Search - flowers",
    "totalResults": 10300000,
    "searchTerms": "flowers",
    "count": 10,
    "startIndex": 11,
    "inputEncoding": "utf8",
    "outputEncoding": "utf8",
    "cx": "013036536707430787589:_pqjad5hr1a"
   }
  ],

我想为上面的回复创建“GoogleResults”类

1 个答案:

答案 0 :(得分:2)

问题是您在没有导入的情况下使用非限定名称引用了GoogleResults类。

使用完全限定名称或导入它。我会发一个例子,但我不确定这个课的位置。

编辑:通过搜索您发布的代码,我找到了complete example。事实证明GoogleResults不是标准的库类,它是一个你应该自己定义的类。

class GoogleResults{

    private ResponseData responseData;
    public ResponseData getResponseData() { return responseData; }
    public void setResponseData(ResponseData responseData) { this.responseData = responseData; }
    public String toString() { return "ResponseData[" + responseData + "]"; }

    static class ResponseData {
        private List<Result> results;
        public List<Result> getResults() { return results; }
        public void setResults(List<Result> results) { this.results = results; }
        public String toString() { return "Results[" + results + "]"; }
    }

    static class Result {
        private String url;
        private String title;
        public String getUrl() { return url; }
        public String getTitle() { return title; }
        public void setUrl(String url) { this.url = url; }
        public void setTitle(String title) { this.title = title; }
        public String toString() { return "Result[url:" + url +",title:" + title + "]"; }
    }
}