Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save JENA Sparql Query ResultSet as JSON?

How do I store the JENA ResultSet as JSON formatted string? I'm currently only able to get the ResultSet to output to the System.out console, but I can't save that to a java String. This is an example of where I'm at:

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?

I want to be able to send the JSON variable to another method to perform some work on it.

Thanks in advance!

like image 488
Pat Grady Avatar asked Jan 18 '26 03:01

Pat Grady


1 Answers

Try writing to a ByteArrayOutputStream and converting the bytes from that to a 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);
like image 160
kevinpeterson Avatar answered Jan 19 '26 19:01

kevinpeterson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!