Googles Freebase API: a basic example of MQL Query and JSON Parse in Java?

Question

What would a basic example of a Freebase query with MQL from the Java Freebase API (google-api-services-freebase) look like and what is the recommended way to process the received data?

I am particularly interested in how to "use" the com.google.api.services.freebase.Freebase class correctly.

Background - what I still have

I have these dependencies in my project:

 <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> 

Now with the following code, I can get unparsed JSON results for stdout:

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

But what is the recommended way to parse the returned JSON? Why do I even want to use the Freebase API if I have to manually parse the JSON result stream?

NB: ultimately, I would like to request large amounts of data; The above query is a simple example.

+4
source share
1 answer

You’re right, because the standard Google Java client library currently doesn’t have many advantages, just forcing the Freebase API to call itself. This is due to the fact that the Freebase MQL API can return arbitrarily complex JSON data, which makes it difficult to work with the client library. I like the json-simple library for analyzing the results.

The following snippet uses the Google HTTP client library and json-simple to issue a Freebase request and analyze the result.

 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()); } 
+4
source

Source: https://habr.com/ru/post/1502395/


All Articles