apachecamel:我不能从实体中取出一个对象并对其进行转换

erhoui1w  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(206)

这里是if do so:body->string->user

.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)))

控制台输出:空
原因是什么?我怎样才能解决这个问题?

hrysbysz

hrysbysz1#

如果您想将json字符串处理到java对象进程,可以将其添加为封送处理程序-https://camel.apache.org/components/latest/dataformats/jacksonxml-dataformat.html

b1uwtaje

b1uwtaje2#

第一个选项将作为json负载的字符串反序列化到对象。它使用jacksons objectmapper来实现这一点。

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

第二个选项没有使用jackson,它没有关于json的任何线索,它试图将有效负载转换为用户对象。但是这不起作用,因为负载是一个json字符串。
我猜它也有类似的作用

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

因此返回值为 null 因为camel在body中找不到用户数组。
如果告诉camel消息体中需要什么数据类型,但消息体不包含此数据类型,camel将返回 null .

相关问题