在使用 OpenFeign 进行远程调用时,如果接口返回的是 List 类型的数据,可以通过以下方式处理:
直接定义返回类型为List
Feign 默认支持 JSON 序列化/反序列化,如果服务端返回的是 List的JSON格式数据,可以直接在 Feign 接口中定义返回类型为 List。
@FeignClient(name = "item-service")
public interface ItemClient {@GetMapping("/items")List<Item> getItems();
}
使用ResponseResult包装返回类型
@FeignClient(name = "item-service")
public interface ItemClient {@GetMapping("/items")ResponseResult<List<Item>> getItems();
}
使用 ResponseResult包装返回类型时,调用 Feign 客户端获取数据时,需要先将data转成JSON字符串,再将JSON字符串解析为List<Item>
ResponseResult responseResult = itemClient.getItems();
String itemsJson = JSON.toJSONString(responseResult.getData());
List<Item> items = JSON.parseArray(itemsJson, Item.class);
直接强制转换
List<Map<String, Object>>
到List<WmChannel>
是不安全的,因为Java的泛型在运行时会被擦除,编译器无法检查具体的类型是否匹配。而JSON会根据目标类的定义,逐个字段地将数据映射到对象中,从而确保类型安全。
List<WmChannel> wmChannels = (List<WmChannel>)responseResult.getData();