![](/img/trans.png)
[英]Serving RDF/XML and JSON-LD representation of Java model with Spring Data Rest?
[英]Serving RDF representation of Java model with Spring MVC?
如何通过Spring MVC提供Java模型的RDF表示形式?
我有使用Spring的内容协商机制工作的JSON和XML表示形式,并且希望对RDF进行相同的处理。
假设您正在为MVC应用程序使用注释驱动的配置,这实际上可能非常简单。 使用W3C的文本RDF格式的媒体类型问题作为内容类型规范的指南,可以很容易地扩展您现有的解决方案。 真正的问题是,当请求RDF时,您需要什么序列化类型? 如果我们将Jena用作基础模型技术,则支持任何标准序列化都是非常简单的。 杰森是唯一给我带来一点困难的人,但是您已经解决了这个问题。
如您所见,序列化的实现(使用标准的Jena,没有其他库)实际上很容易做到! 问题最终只是将适当的序列化与提供的内容类型匹配。
编辑2014年4月19日
先前的内容类型来自捕获工作组讨论的文档。 该帖子经过编辑以反映IANA媒体类型注册表的内容类型,并以RDF1.1 N-Triples和JSON-LD标准为补充。
@Controller
public class SpecialController
{
public Model model = null; // set externally
@RequestMapping(value="your/service/location", method=RequestMethod.GET, produces={"application/x-javascript", "application/json", "application/ld+json"})
public @ResponseBody String getModelAsJson() {
// Your existing json response
}
@RequestMapping(value="your/service/location", method=RequestMethod.GET, produces={"application/xml", "application/rdf+xml"})
public @ResponseBody String getModelAsXml() {
// Note that we added "application/rdf+xml" as one of the supported types
// for this method. Otherwise, we utilize your existing xml serialization
}
@RequestMapping(value="your/service/location", method=RequestMethod.GET, produces={"application/n-triples"})
public @ResponseBody String getModelAsNTriples() {
// New method to serialize to n-triple
try( final ByteArrayOutputStream os = new ByteArrayOutputStream() ){
model.write(os, "N-TRIPLE");
return os.toString();
}
}
@RequestMapping(value="your/service/location", method=RequestMethod.GET, produces={"text/turtle"})
public @ResponseBody String getModelAsTurtle() {
// New method to serialize to turtle
try( final ByteArrayOutputStream os = new ByteArrayOutputStream() ){
model.write(os, "TURTLE");
return os.toString();
}
}
@RequestMapping(value="your/service/location", method=RequestMethod.GET, produces={"text/n3"})
public @ResponseBody String getModelAsN3() {
// New method to serialize to N3
try( final ByteArrayOutputStream os = new ByteArrayOutputStream() ){
model.write(os, "N3");
return os.toString();
}
}
}
另外,您必须添加charset
参数。 除非您进行更改,否则StringHttpMessageConverter用作ISO-8859-1的默认字符编码。 当输出格式具有不同于ISO-8859-1的固定编码(例如UTF-8)时,必须在produces
声明它。 此行为与规格一致。 例如,当模型包含非ASCII字符并且以turtle
编码时,规范说明介质类型text / turtle必须包含参数charset
和值UTF-8
。 否则,它是可选的。
@RequestMapping(value = "your/service/location", method = RequestMethod.GET,
produces = { "text/turtle;charset=UTF-8"})
public @ResponseBody String getModelAsTurtle() throws IOException {
try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) {
RDFDataMgr.write(os, model, RDFFormat.TURTLE_PRETTY);
return os.toString();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.