0

I need to export SPARQL query results into JSON using Sesame. Should I use the class SPARQLResultsJSONWriter? How would this be implemented (in Java)?

4

1 回答 1

5

这实际上在 Sesame Repository API用户文档中进行了解释,并带有代码示例进行演示。

但是,重申一下:一旦您使用RepositoryConnection.prepareTupleQuery准备好查询,您可以通过两种方式评估返回的TupleQuery对象:一种是调用evaluate(),在这种情况下,评估方法将返回一个 TupleQueryResult 对象。另一种是调用evaluate(TupleQueryResultHandler)并传递一个TupleQueryResultHandler实例,SPARQLResultJSONWriter 是它的子类。所以你需要做的就是把这些碎片放在一起,就像这样:

RepositoryConnection conn = rep.getConnection();
try {
   // prepare the query
   String queryString = "SELECT * WHERE {?s ?p ?o . }";
   TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString);

   // open a file to write the result to it in JSON format
   OutputStream out = new FileOutputStream("/path/to/output.json");
   TupleQueryResultHandler writer = new SPARQLResultJSONWriter(out);

   // execute the query and write the result directly to file
   query.evaluate(writer);  
}
finally {
   conn.close();
}
于 2013-09-05T23:07:53.763 回答