显示搜索结果

时间:2012-10-31 16:18:24

标签: java json gson

我一直在玩GSON和JSON来完成搜索并显示结果。我有这段代码,但我无法显示结果:

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

    String google = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";
    String search = "food pantries in Dallas";
    String charset = "UTF-8";

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


    // Show title and URL of 1st result.
    System.out.println(results.getResponseData().getResults().get(0).getTitle());
    System.out.println(results.getResponseData().getResults().get(0).getUrl());
    System.out.println(results.getResponseData().getResults());

}

更新:

我可以使用搜索获得一些结果,并显示列表:

<b>Food Pantries</b> | Soup Kitchens | <b>Food Banks</b>
http://www.foodpantries.org/
[Result[url:http://www.foodpantries.org/,title:<b>Food Pantries</b> | Soup Kitchens | <b>Food Banks</b>], Result[url:http://feedingamerica.org/foodbank-results.aspx,title:Find a Local <b>Food Bank</b> | Feeding America], Result[url:http://www.foodbanknyc.org/,title:<b>Food Bank</b> for New York City], Result[url:http://en.wikipedia.org/wiki/Food_bank,title:<b>Food bank</b> - Wikipedia, the free encyclopedia]]

我正在尝试创建清洁列表,显示此结果仅显示网站,也许还有更多信息。

我在考虑使用Jsoup,但不确定如何整合这两者。有什么建议?

谢谢,

理查德。

1 个答案:

答案 0 :(得分:0)

Richard,假设您的GoogleResults类是一个与响应中的属性匹配的java bean,您只需要对搜索查询进行正确编码:

变化:

URL url = new URL(google + search);

为:

URL url = new URL(google + URLEncoder.encode(search,"UTF-8"));