【问题标题】:Unmarshaling JSON array to POJO object将 JSON 数组解组为 POJO 对象
【发布时间】:2020-04-23 06:56:33
【问题描述】:

我正在使用骆驼弹簧,我收到一个 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")

错误:

无法反序列化 START_ARRAY 中的 com.liena.Response 实例 令牌

有没有办法将 JSON 数组直接解组到我的对象?

【问题讨论】:

    标签: java json spring apache-camel


    【解决方案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);
       ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-13
      • 1970-01-01
      • 2023-03-22
      • 2020-05-02
      • 2019-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多