I have a Jena model that I extract from a SPARQL CONSTRUCT
, I want to translate it into JSON-LD, with the Embed feature, ie, if person1 knows person2
, I want the person2
object inside person1, linked by the knows property.
Following examples around (1, 2), I've managed to do it through the setup of a context object:
Model m = SparqlUtils.construct ( sparql, model ); // yeah, I want JSON from a CONSTRUCT-extracted subgraph
StringWriter sw = new StringWriter ();
JsonLDWriteContext ctx = new JsonLDWriteContext ();
JsonLdOptions opts = new JsonLdOptions ();
opts.setEmbed ( "@always" );
ctx.setOptions ( opts );
Map<String, Object> frctx = new HashMap<> ( NamespaceUtils.getNamespaces () ); // this is just a map of prefix->uri
Map<String, String> knows = new HashMap<> ();
knows.put ( "@id", "foaf:knows" );
knows.put ( "@type", "@id" );
frctx.put ( "knows", knows );
frctx.put ( "name", "foaf:name" );
Map<String, Object> frame = new HashMap<> ();
frame.put ( "@type", "foaf:Person" );
frame.put ( "@context", frctx );
ctx.setFrame ( frame );
Graph graph = m.getGraph ();
PrefixMap prefixes = RiotLib.prefixMap ( graph );
WriterGraphRIOT writer = RDFDataMgr.createGraphWriter ( RDFFormat.JSONLD_FRAME_PRETTY );
writer.write ( sw, graph, prefixes, null, ctx );
However, I'm not happy at all with this solution, since I would be just fine with the default '@context', but if I don't set any frame into the ctx
object that is passed to write()
, I get an error that the context is missing. On the other hand, if I call write()
with another format (eg, JSONLD_COMPACT_PRETTY
), the ctx
object seems to be ignored by the writer, ie, @embed = @always
is ignored and the JSON I get is the usual list of flat objects, with the URIs as "knows" values.
How can I do it? Is there a way to get the default context? Is there a simpler way to tell about the embed option?