【发布时间】:2021-09-24 22:00:09
【问题描述】:
我有一个应用程序,当我调用它的一项服务时,它会返回以下 JSON:
{
"suppliers": [
{
"name": "Joaquim",
"email": "joaquim@email.com",
},
{
"name": "Manoel",
"email": "manoel@email.com",
}
]
}
为了访问这些数据,我使用了一个具有以下方法的 Feign 客户端:
@FeignClient(name = "suppliersClient", url = "www.url-example.com.br")
// ...
List<SuppliersDTO> searchSuppliers(@RequestParam("city") String city);
根据城市,它会返回供应商列表。这段代码是一个简单的例子,向你解释我想要做什么。
除了 getters 和 setters 之外,我的 DTO 供应商类还有 name 和 email 字段。
public class SuppliersDTO {
String name;
String email;
// GETTERS AND SETTERS
使用这样的代码,当使用 Feign 客户端时,我得到一个 500 Internal Server Error 的信息:
"Error while extracting response for type [java.util.List<com.domain.store.dto.SuppliersDTO>] and content type [application/json;charset=utf-8]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.util.ArrayList<com.domain.store.dto.SuppliersDTO>` from Object value (token `JsonToken.START_OBJECT`); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `java.util.ArrayList<com.domain.store.dto.SuppliersDTO>` from Object value (token `JsonToken.START_OBJECT`)\n at [Source: (PushbackInputStream); line: 1, column: 1]"
根据我的研究和阅读,发生错误是因为服务的 JSON 返回一个供应商对象,并且其中有一个列表。这就是杰克逊无法绑定到我的List<SuppliersDTO> 的原因。为了解决这个问题,我创建了另一个类:
public class SuppliersListDTO {
List<SuppliersDTO> suppliers;
// GETTERS E SETTERS
现在我的 Feign 返回 SuppliersListDTO 而不是 List<SuppliersDTO>:
@FeignClient(name = "SuppliersClient", url = "www.url-example.com.br")
// ...
SuppliersListDTO searchSuppliers(@RequestParam("city") String city);
这样就可以了,绑定完成,我返回一个 SuppliersListDTO 给用户。但这似乎不是处理从 JSON 接收到的列表的最正确方法。我真的必须为此创建两个 DTO 类,其中一个只有一个变量 (List<SuppliersDTO> suppliers) 及其getter 和setter?根据您的经验,您会推荐另一种方法吗?
【问题讨论】:
-
你有两个 JSON 对象。具有供应商属性的供应商对象列表。对我来说似乎很直接
-
你有这个注解@EnableFeignClients 吗?
-
@TiagoMedici 是的,我有这个注释。
-
告诉我你在哪里自动装配 feign 接口
标签: java spring-boot spring-mvc spring-cloud spring-cloud-feign