2015-10-07 89 views
3

如何將JENA ResultSet存儲爲JSON格式的字符串?我目前只能夠將ResultSet輸出到System.out控制檯,但我無法將其保存到java字符串中。這是我在其中一個例子:我希望能夠到JSON變量發送到其他的方法來對它進行一些工作如何將JENA Sparql查詢結果集保存爲JSON?

QueryExecution qexec = QueryExecutionFactory.sparqlService(endpoint, query); 
ResultSet results = qexec.execSelect(); 
// the following prints out JSON in the System.out console: 
ResultSetFormatter.outputAsJSON(System.out, results); 
// but how do I save it as a String? 
// ie. 
String json = ResultSetFormatter.outputAsJSON(System.out, results); 
// obviously that doesn't work, but how would one get the equivalent working version? 

在此先感謝!

回答

6

嘗試寫入ByteArrayOutputStream,並從該變換的字節到String

QueryExecution qexec = QueryExecutionFactory.sparqlService(sparqlEndpointQuery, query); 
ResultSet results = qexec.execSelect(); 

// write to a ByteArrayOutputStream 
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 

ResultSetFormatter.outputAsJSON(outputStream, results); 

// and turn that into a String 
String json = new String(outputStream.toByteArray()); 

System.out.println(json);