如何在Micronaut声明式客户端中提取响应JSON字段?
问题解答
在Micronaut 3.4.4版本中完全可以实现直接提取foos数组并返回List<Foo>,无需声明额外的响应包装类,最简洁的方式是使用@JsonPath注解指定JSON路径提取目标内容:
解决方案代码修改
修改你的声明式客户端方法,添加@JsonPath注解并指定提取路径$.foos,同时将返回类型改为List<Foo>:
@Client(id="third-party-service", path="/3.0") @Header(name=HttpHeaders.ACCEPT, value="application/problem+json, application/json") public interface ThirdPartyClient { @Get("/items/{item-id}/categories/{category-id}/foos") @JsonPath("$.foos") // 指定提取JSON中的foos数组 List<Foo> fetchFoos( @NonNull @PathVariable("item-id") String itemId, @NonNull @PathVariable("category-id") String categoryId); }
原理说明
@JsonPath注解是Micronaut集成Jackson提供的功能,它会指示客户端的JSON解析器直接从响应的JSON结构中定位到$.foos路径对应的数组节点,自动将其映射为List<Foo>类型,跳过外层的包装对象。
需要确保你的项目中已包含Micronaut Jackson相关依赖(Micronaut 3.x项目默认会引入),无需额外配置。
内容的提问来源于stack exchange,提问作者Cromax
相关产品推荐
相关产品推荐

