我正在尝试使用 Camel 中的 Rest DSL 处理一个 csv 文件。
当我将 CSV 和 Marshall 拆分为 JSON 时,我遇到了一些奇怪的行为。这是我的代码:
@Component
public class
ProcessHandler extends RouteBuilder {
@Override
protected void defineRoute() throws Exception {
DataFormat csv = new BindyCsvDataFormat(CsvModel.class);
rest("/")
.post().produces("application/json")
.route()
.unmarshal(csv)
.split(body()).parallelProcessing().streaming()
.marshal().json(JsonLibrary.Gson)
.filter().jsonpath("$[?(@.counter==3)]")
.log("${body}")
但是我收到错误消息:从类型转换时出错:java.lang.String 到所需类型:byte[] with value [CsvModel(....
但是,如果我按如下方式编辑路线:
@Component
public class
ProcessHandler extends RouteBuilder {
@Override
protected void defineRoute() throws Exception {
DataFormat csv = new BindyCsvDataFormat(CsvModel.class);
rest("/")
.post().produces("application/json")
.route()
.unmarshal(csv)
.marshal().json(JsonLibrary.Gson)
.split(body()).parallelProcessing().streaming()
//.filter().jsonpath("$[?(@.counter==3)]")
.log("${body}")
它工作正常。
然而,我显然无法正确处理我的消息,因为它被编码为字节表示。如果不使用 Rest DSL,该路由也能正常工作,所以我假设问题出在 http 响应上。如果我尝试以下操作:
@Component
public class
ProcessHandler extends RouteBuilder {
@Override
protected void defineRoute() throws Exception {
DataFormat csv = new BindyCsvDataFormat(CsvModel.class);
rest("/")
.post().produces("application/json")
.route()
.unmarshal(csv)
.marshal().json(JsonLibrary.Gson)
.split(body()).parallelProcessing().streaming()
.unmarshal().json(JsonLibrary.Gson)
.filter().jsonpath("$[?(@.counter==3)]")
.marshal().json(JsonLibrary.Gson)
.log("${body}")
我得到了同样的错误。能不能规范化格式,做一些处理步骤,然后返回一个Json?我哪里出错了 - 我希望能理解为什么会这样?
最佳答案
如果您在内部使用过滤而不是使用 JsonPath 来实现聚合策略,可能会更容易,因此更容易理解。
事实上,如果默认使用 split()
方法,将不会给出您期望的结果
这是一个例子:
@Component
public class ProcessHandler extends RouteBuilder {
@Override
protected void defineRoute() throws Exception {
DataFormat csv = new BindyCsvDataFormat(CsvModel.class);
rest("/")
.post().produces("application/json")
.route()
.unmarshal(csv)
.split().method(ItemsSplittingStrategy.class, "splitItems")
.parallelProcessing()
.marshal().json(JsonLibrary.Gson)
.end()
.to("file:/file.json");
}
}
在您的 ItemsSplittingStrategy
类中,您是否进行过滤。您可以找到一个简单、明确的示例 here
我还邀请您检查可用于拆分器和聚合器及其组合的所有功能。
关于java - Apache Camel - 在 Rest DSL 中编码到 Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57581040/