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

Viewed 1506

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?

2 Answers

The first option deserializes a String that is a JSON payload to Objects. It uses Jacksons ObjectMapper to do this.

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

The second option does not use Jackson, it has no clue about JSON it tries to cast the payload to User objects. But this does not work, because the payload is a JSON String.

I assume it does something similar like this

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

Therefore the return value is null because Camel can't find a User array in the body.

If you tell Camel what datatype you expect in the message body but the body does not contain this datatype, Camel returns null.

Related