Groovy如何提取JSON数组中translations->ita->common字段
问题解决方案
1. 修正API请求参数
你当前的fields参数写法错误,restcountries的字段筛选支持用.指定嵌套路径,原参数translations,ita,common会尝试返回顶层的三个独立字段(但顶层不存在ita和common),正确写法应该是translations.ita.common,这样接口只会返回我们需要的嵌套字段,减少冗余数据传输。
2. 遍历数组提取目标字段
接口返回的是JSON数组,每个元素对应一个国家对象,我们可以通过Groovy的collect方法遍历数组,批量提取目标字段值。
修正后的完整代码
import groovyx.net.http.HTTPBuilder import static groovyx.net.http.ContentType.JSON import static groovyx.net.http.Method.GET import groovy.json.JsonOutput HTTPBuilder getHttpBuilder() { new HTTPBuilder('https://restcountries.com/') } def http = getHttpBuilder().request(GET, JSON){ uri.path = 'v3.1/all' // 修正嵌套字段的筛选路径 uri.query = [fields: 'translations.ita.common'] response.success = { resp, json -> // 遍历数组,提取每个国家的意大利语通用名称 def italianCountryNames = json.collect { country -> country.translations.ita.common } // 打印提取结果 log.info("意大利语国家名称列表:") italianCountryNames.each { name -> log.info(name) } // 格式化输出完整列表 log.info(JsonOutput.prettyPrint(JsonOutput.toJson(italianCountryNames))) } // 新增失败回调,便于排查请求错误 response.failure = { resp -> log.error("请求失败,状态码:${resp.statusLine.statusCode}") } }
额外说明(如果需要保留完整数据)
如果不想限制接口返回字段,也可以直接在遍历中提取目标值,同时用安全导航操作符?.避免空指针异常:
response.success = { resp, json -> def italianCountryNames = json.collect { country -> // 若某个国家无对应字段,返回默认值 country?.translations?.ita?.common ?: '无意大利语名称' } // 后续处理逻辑... }
内容的提问来源于stack exchange,提问作者TheShestov
相关产品推荐
相关产品推荐

