java - 如何使用OpenFeign获取pojo数组?

标签 java arrays json gson netflix-feign

我正在尝试使用 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 并直接返回 POJO,所以我正在尝试这个

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

我遇到了这个错误

feign.codec.DecodeException:java.lang.IllegalStateException:预期为 BEGIN_ARRAY,但在第 1 行第 2 列路径 $ 处为 STRING $

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

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

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

  • 修剪响应并删除有效负载开头和结尾的所有空格
  • 删除所有 new_line 字符,例如:\r\n\r\n

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

关于java - 如何使用OpenFeign获取pojo数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55012543/

相关文章:

java - 使用if语句来防止 "java.lang.IndexOutOfBoundsException"

ios - 在 swift 4 中修改 [UInt8] 字节数组的最佳方法是什么?

java - 访问单独类中的数组时出现问题

javascript - json 字符串转为 javascript 对象

同一类和相同实现中的 JAVA 方法,但作为参数的对象类型不同

java - 如何编辑我的比较方法

java - 分离多个JTable

C++,没有STL和Boost的对象数组(来自不同的类)

javascript - 如何在本地存储中存储对象

json - 如何使用mssql递归解析JSON字符串?