我有一个从SPARQL CONSTRUCT
中提取的Jena模型,我想用Embed feature将其转换为JSON-LD,即如果person1 knows person2
,我想要在person1内部的person2
对象,由Knows属性链接。
以下(1,2)的示例中,我设法通过设置上下文对象来做到这一点:
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 );
但是,我对这个解决方案一点都不满意,因为我对默认的'@context'没问题,但是如果我不对传递的ctx
对象设置任何框架到write()
,我收到一个上下文丢失的错误消息。另一方面,如果我以另一种格式(例如write()
)调用JSONLD_COMPACT_PRETTY
,则ctx
对象似乎被编写者忽略了,即@embed = @always
被忽略了而我得到的JSON是通常的平面对象列表,其中URI为“知道”值。
我该怎么办?有没有办法获取默认上下文?有没有一种简单的方式来介绍embed选项?