我正在尝试使用 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/