Camel 正在将JSON数组解组为POJO对象

zc0qhyus  于 2022-11-07  发布在  Apache
关注(0)|答案(1)|浏览(170)

我正在使用camel-spring,我从API收到一个JSON数组作为响应,如下所示:

[{"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")

错误:
无法反序列化com.利耶纳的示例。响应超出START_ARRAY标记
有没有办法将JSON数组直接解组到我对象?

rkue9o1l

rkue9o1l1#

我通过在我的处理器中使用对象Map器解决了这个问题。
我的路线生成器:

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);
   ...
}

相关问题