如何使用OpenFeign获取pojo数组?

How to use OpenFeign to get a pojo array?

我正在尝试使用 OpenFeign 客户端点击 API,获取一些 JSON,并将其转换为 POJO 数组。

以前我只是得到一个 JSON 的字符串,然后使用 Gson 将其转换为数组,就像这样

FeignInterface {
    String get(Request req);
}
String json = feignClient.get(request);
POJO[] pojoArray = new Gson().fromJson(json, POJO[].class);

这是有效的。我想消除额外的步骤并假装自动解码 JSON 和 return 一个 POJO,所以我正在尝试这个

FeignInterface {
    POJO[] get(Request req);
}
POJO[] pojoArray = feignClient.getJsonPojo(request);`

我运行遇到了这个错误

feign.codec.DecodeException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 2 path $

两种方法使用相同的构建器

feignClient = Feign.builder()
     .encoder(new GsonEncoder())
     .decoder(new GsonDecoder())
     .target(FeignInterface.class, apiUrl);

有人有什么想法吗?

您破坏了 JSON 负载。在序列化之前,您需要删除所有不受支持的字符。 Feign 允许这样:

If you need to pre-process the response before give it to the Decoder, you can use the mapAndDecode builder method. An example use case is dealing with an API that only serves jsonp, you will maybe need to unwrap the jsonp before send it to the Json decoder of your choice:

public class Example {
  public static void main(String[] args) {
    JsonpApi jsonpApi = Feign.builder()
         .mapAndDecode((response, type) -> jsopUnwrap(response, type), new GsonDecoder())
         .target(FeignInterface.class, apiUrl);
  }
}

因此,您需要在配置中执行相同的操作并且:

  • trim响应并删除所有whitespaces payload的开头和结尾。
  • 删除所有 new_line 个字符,例如:\r\n\r\n

使用 online tool 确保您的 JSON 负载有效并准备反序列化。