java - 谷歌的 Freebase API : Basic MQL Query and JSON Parse Example in Java?

标签 java json freebase google-api-java-client mql

问题

从 Java Freebase API (google-api-services-freebase) 使用 MQL 查询 Freebase 的基本示例是什么样的?处理结果数据的推荐方法是什么?

我特别想知道如何“正确”使用 the com.google.api.services.freebase.Freebase class .

背景——我目前的情况

我的项目中有这些依赖项:

<dependency>
  <groupId>com.google.apis</groupId>
  <artifactId>google-api-services-freebase</artifactId>
  <version>v1-rev42-1.17.0-rc</version>
</dependency>
<dependency>
  <groupId>com.google.http-client</groupId>
  <artifactId>google-http-client-jackson2</artifactId>
  <version>1.17.0-rc</version>
</dependency>

现在使用以下代码,我可以将未解析的 JSON 结果输出到标准输出:

Freebase freebase = new Freebase(
    GoogleNetHttpTransport.newTrustedTransport(),
    JacksonFactory.getDefaultInstance(),
    null);
Mqlread mqlread = freebase.mqlread(
    "[{ \"limit\": 5, \"name\": null, \"type\": \"/medicine/disease\" }]");
mqlread.executeAndDownloadTo(System.out);

但是推荐的解析返回的 JSON 的方法是什么?如果无论如何我都必须手动解析 JSON 结果流,我为什么还要使用 Freebase API?

注意:最终我想查询更多的数据;上面的查询只是一个简单的例子。

最佳答案

您是对的,因为它目前代表标准的 Google Java 客户端库并没有比您自己调用 Freebase API 提供更多好处。这是因为 Freebase MQL API 可以返回任意复杂的 JSON 数据,这使得客户端库很难对其进行任何花哨的操作。我喜欢json-simple用于解析结果的库。

以下代码段使用 Google HTTP client library和 json-simple 发出 Freebase 查询并解析结果。

HttpTransport httpTransport = new NetHttpTransport();
HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
JSONParser parser = new JSONParser();
String query = "[{\"limit\": 5,\"name\":null,\"type\":\"/medicine/disease\"}]";
GenericUrl url = new GenericUrl("https://www.googleapis.com/freebase/v1/mqlread");
url.put("key", "YOUR-API-KEY-GOES-HERE");
url.put("query", query);
HttpRequest request = requestFactory.buildGetRequest(url);
HttpResponse httpResponse = request.execute();
JSONObject response = (JSONObject)parser.parse(httpResponse.parseAsString());
JSONArray results = (JSONArray)response.get("result");
for (Object result : results) {
  System.out.println(result.get("name").toString());
}

关于java - 谷歌的 Freebase API : Basic MQL Query and JSON Parse Example in Java?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18826850/

相关文章:

freebase - 在 Freebase 中查询所有诺贝尔和平奖获得者

javascript - 使用 Rails 3.1 Assets 管道包括外部库

javascript - 在 for 语句中使用 parseJSON 数据?

java - 在正确的位置向 java 数组添加值

java - 解析 XML 最快的方法是什么?

java - 在eclipse中是否可以自动向所有项目添加一个设置的外部jar?

php - 从android中的mysql数据库中检索edittext中的数据

json - MongoDB查询列表中的对象属性

javascript - 解析 Freebase 主题 HTTP API - JSON 和 Javascript

JAVA java.util.ConcurrentModificationException :null Exception