Issue
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:
class="lang-java prettyprint-override">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
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);
...
}
Answered By - L.G
Answer Checked By - Marilyn (JavaFixing Volunteer)