Apache Camel:我无法从体内取出物体并对其进行转换

Apache Camel: I can't get an object out of the body and transform it

这是如果这样做:正文 -> 字符串 -> 用户

    .to("direct:httpClient")
    .process(new Processor() {
        @Override
        public void process(Exchange exchange) throws JsonProcessingException {
            String body = exchange.getIn().getBody(String.class);
            User[] users = jacksonDataFormat.getObjectMapper().readValue(body, User[].class);
        }
    })

此选项效果很好,但如果您这样做:

User [] body = exchange.getIn().getBody(User[].class);

正文 -> 用户,它不起作用。用户始终为空。

为清楚起见:

from("timer://test?period=2000")
                .setHeader(Exchange.HTTP_METHOD).constant(HttpMethod.GET)
                .setHeader(Exchange.CONTENT_TYPE, constant("application/json"))
                .convertBodyTo(User[].class)
                .to("http://localhost:8085/api/user")
                .process(exchange -> System.out.println(exchange.getIn().getBody(String.class)))

控制台输出:

[
   {
      "name":"BLA"
   },
   {
      "name":"BLA"
   },
   {
      "name":"BLA"
   }
]

如果是:

from("timer://test?period=2000")
                .setHeader(Exchange.HTTP_METHOD).constant(HttpMethod.GET)
                .setHeader(Exchange.CONTENT_TYPE, constant("application/json"))
                .convertBodyTo(User[].class)
                .to("http://localhost:8085/api/user")
                .process(exchange -> System.out.println(exchange.getIn().getBody(User[].class)))

控制台输出:空

这是什么原因?我该如何解决这个问题?

第一个选项将作为 JSON 负载的字符串反序列化为对象。它使用 Jacksons ObjectMapper 来做到这一点。

Camel > get body as String
Jackson > parse String to JSON and deserialize it to Objects

第二个选项不使用 Jackson,它对 JSON 毫无头绪,它 尝试将有效负载投射到用户对象 。但这不起作用,因为有效负载是 JSON String.

我假设它会做类似这样的事情

if (body instanceof User[]) {
    return (User[]) body;
} else {
    return null;
}

因此return的值是null因为Camel在正文中找不到用户数组。

如果您在消息正文中告诉 Camel 您期望的数据类型,但正文不包含此数据类型,Camel returns null.

如果你想让 Camel 处理 JSON 字符串到 Java 对象进程,你可以将它添加为编组器 - https://camel.apache.org/components/latest/dataformats/jacksonxml-dataformat.html