문제

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

도움이 되었습니까?

해결책

This is actually explained in the Sesame Repository API user documentation, with code examples to demonstrate.

However, to reiterate: once you have prepared a query by using RepositoryConnection.prepareTupleQuery, you can evaluate the returned TupleQuery object in two ways: one is by calling evaluate(), in which case the evaluation method will return a TupleQueryResult object. The other is by calling evaluate(TupleQueryResultHandler) and passing it a TupleQueryResultHandler instance, of which SPARQLResultJSONWriter is a subclass. So all you need to is bring the pieces together, like so:

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();
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top