'Unmarshaling JSON array to POJO object

I'm working with camel-spring, I receive a JSON array as a response from an API as below:

[{"userName":"name","email":"email"}]

My object like this:

public class Response{

    private String userName;
    private String email;
    
    // setters & getters

}

My route builder:

from("seda:rout")
          .routeId("distinaation")
          .unmarshal()
          .json(JsonLibrary.Jackson, Request.class)
          .bean(Bean.class, "processRequest")
          .to(destination)
          .unmarshal()
          .json(JsonLibrary.Jackson, Response.class)
          .bean(Bean.class, "processResponse")

error:

Can not desserialize instance of com.liena.Response out of START_ARRAY token

is there any way to unmarshal a JSON array directly to my object?



Solution 1:[1]

I solved the problem by using object mapper in my processor.

My route builder :

from("seda:rout")
          .routeId("distinaation")
          .unmarshal()
          .json(JsonLibrary.Jackson, Request.class)
          .bean(Bean.class, "processRequest")
          .to(destination)
          .bean(Bean.class, "processResponse")

processor:

public Response processResponse(Exchange exchange) throws IOException {
    String responseStr = exchange.getIn().getBody().toString();
    ObjectMapper mapper = new ObjectMapper();
    List<Response> list = mapper.readValue(responseStr, new TypeReference<List<Response>>(){};
    Response response = list.get(0);
    ...
}

Another short way to do this is:

In route builder :

from("seda:rout")
          .routeId("distinaation")
          .unmarshal()
          .json(JsonLibrary.Jackson, Request.class)
          .bean(Bean.class, "processRequest")
          .to(destination)
          .unmarshal(new ListJacksonDataFormat(Response.class))
          .bean(Bean.class, "processResponse")

processor:

public Response processResponse(List<Response> list {
   Response response = list.get(0);
   ...
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mark Rotteveel