我正在使用骆驼弹簧,我将Json数组作为来自api的响应,如下所示:
[{"userName":"name","email":"email"}]
我的对象是这样的:
public class Response{
private String userName;
private String email;
setters & getters
}
我的路线创建者:
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")
错误:
Can not desserialize instance of com.liena.Response out of START_ARRAY token
有什么方法可以直接将json数组解组到我的obj吗?
答案 0 :(得分:1)
我通过在处理器中使用对象映射器解决了这个问题。
我的路线创建者:
from("seda:rout")
.routeId("distinaation")
.unmarshal()
.json(JsonLibrary.Jackson, Request.class)
.bean(Bean.class, "processRequest")
.to(destination)
.bean(Bean.class, "processResponse")
处理器:
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);
...}
执行此操作的另一个简短方法是: 在路径生成器中:
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")
处理器:
public Response processResponse(List<Response> list {
Response response = list.get(0);
...
}