Apache Camel:我无法从身体中取出物体并对其进行改造

2022-01-19 00:00:00 json spring java jackson apache-camel

如果这样做的话,这里是:body ->字符串->用户

 .to("direct:httpClient").process(新处理器(){@覆盖公共无效进程(交换交换)抛出 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, 常量("application/json")).convertBodyTo(用户[].class).to("http://localhost:8085/api/user").process(exchange -> System.out.println(exchange.getIn().getBody(String.class)))

控制台输出:

<代码>[{名称":BLA";},{名称":BLA";},{名称":BLA";}]

如果是这样:

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

控制台输出:null

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

解决方案

如果你想让 Camel 处理 JSON 字符串到 Java 对象的过程,你可以将它添加为 marshaller - https://camel.apache.org/components/latest/dataformats/jacksonxml-dataformat.htmlp>

Here is 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);
        }
    })

This option works great, but if you do this:

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

body -> user, it doesn't work. User always null.

For clarity:

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

Console output:

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

If so:

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

Console output: null

What is the reason? how can I fix this?

解决方案

If you want Camel to handle the JSON string to Java object process, you can add it as a marshaller - https://camel.apache.org/components/latest/dataformats/jacksonxml-dataformat.html

相关文章