我目前正在开发一个基于REST的java应用程序,使用新的Camel REST DSL作为基础。除了我注意到通过REST客户机(而不是浏览器)调用URL时,JSON响应是“乱七八糟的”,我认为是错误的编码。
MyRouteBuilder.java
@Component
public class MyRouteBuilder extends RouteBuilder{
@Autowired
LocalEnvironmentBean environmentBean;
@Override
public void configure() throws Exception {
restConfiguration().component("jetty").host("0.0.0.0").port(80)
.bindingMode(RestBindingMode.auto);
rest("/testApp")
.get("/data").route()
.to("bean:daoService?method=getData")
.setProperty("viewClass", constant(CustomeJsonViews.class))
.marshal("customDataFormat").endRest()
.get("/allData").route()
.to("bean:daoService?method=getDatas")
.setProperty("viewClass", constant(CustomeJsonViews.class))
.marshal("customDataFormat").endRest();
}
}CustomeDataFormat.java
public class CustomDataFormat implements DataFormat{
private ObjectMapper jacksonMapper;
public CustomDataFormat(){
jacksonMapper = new ObjectMapper();
}
@Override
public void marshal(Exchange exchange, Object obj, OutputStream stream) throws Exception {
Class view = (Class) exchange.getProperty("viewClass");
if (view != null)
{
ObjectWriter w = jacksonMapper.writerWithView(view);
w.writeValue(stream, obj);
}
else
stream.write(jacksonMapper.writeValueAsBytes(obj));
}
@Override
public Object unmarshal(Exchange exchange, InputStream stream) throws Exception {
return null;
}
}在这里可以找到一个完整的工作版本:https://github.com/zwhitten/camel-rest-test
以Chrome为例,当转到URL {host}/testApp/data时,响应如下:
{
data: "Sherlock",
value: "Holmes",
count: 10
}但是,使用Postman浏览器插件作为客户端返回:
"W3siZGF0YSI6ImRhdGE6OjAiLCJ2YWx1ZSI6InZhbHVlOjowIiwiY291bnQiOjB9LHsiZGF0YSI6ImRhdGE6OjEiLCJ2YWx1ZSI6InZhbHVlOjoxIiwiY291bnQiOjF9LHsiZGF0YSI6ImRhdGE6OjIiLCJ2YWx1ZSI6InZhbHVlOjoyIiwiY291bnQiOjJ9LHsiZGF0YSI6ImRhdGE6OjMiLCJ2YWx1ZSI6InZhbHVlOjozIiwiY291bnQiOjN9LHsiZGF0YSI6ImRhdGE6OjQiLCJ2YWx1ZSI6InZhbHVlOjo0IiwiY291bnQiOjR9LHsiZGF0YSI6ImRhdGE6OjUiLCJ2YWx1ZSI6InZhbHVlOjo1IiwiY291bnQiOjV9LHsiZGF0YSI6ImRhdGE6OjYiLCJ2YWx1ZSI6InZhbHVlOjo2IiwiY291bnQiOjZ9LHsiZGF0YSI6ImRhdGE6OjciLCJ2YWx1ZSI6InZhbHVlOjo3IiwiY291bnQiOjd9LHsiZGF0YSI6ImRhdGE6OjgiLCJ2YWx1ZSI6InZhbHVlOjo4IiwiY291bnQiOjh9LHsiZGF0YSI6ImRhdGE6OjkiLCJ2YWx1ZSI6InZhbHVlOjo5IiwiY291bnQiOjl9XQ=="问题似乎在于REST绑定模式是“自动”并使用自定义封送处理程序。如果我将绑定模式设置为"json“,那么浏览器和客户端的响应都会被混淆。如果我将绑定模式设置为"json“并绕过自定义封送拆收器,一切都会正常工作。是否有一种方法可以配置路由以使用自定义封送处理程序并正确编码响应,而不管客户端是什么?
发布于 2014-12-04 23:02:07
我认为解决方案是使用默认绑定选项(Off),因为您使用的是自定义封送器。
发布于 2016-07-28 08:18:56
要做到这一点,你有两种方法:
jsonDataFormat配置REST配置以设置自定义数据格式。
Map dataFormats = getContext().getDataFormats();if (dataFormats == null) { dataFormats =新HashMap<>();} dataFormats.put("yourFormat",新DataFormatDefinition(新CustomDataFormat();发布于 2017-01-03 09:54:21
您还可以创建自己的数据格式,如下所示:
在您的custom配置中,它将如下所示(参见json-定制)
builder.restConfiguration().component("jetty")
.host(host(propertiesResolver))
.port(port(propertiesResolver))
.bindingMode(RestBindingMode.json)
.jsonDataFormat("json-custom")
;您必须创建一个文件“json-定制”。
因此,文件的内容应该是:
class=packageofmyclass.MyOwnDataformatterhttps://stackoverflow.com/questions/27301869
复制相似问题