Google Cloud BigQuery查询结果获取失败:NoSuchMethodError错误求助
BigQuery查询报错
NoSuchMethodError: com.google.gson.JsonParser.parseString排查与解决 我尝试从BigQuery数据集中获取计数时,抛出如下错误:
com.google.cloud.bigquery.BigQueryException: java.lang.NoSuchMethodError: com.google.gson.JsonParser.parseString(Ljava/lang/String;)Lcom/google/gson/JsonElement;
相关代码如下:
public static void main(String[] args) { final String datasetName = "users"; String query = " SELECT count(1) " + " FROM preprod.users.records" + " WHERE section_id = 'sectionId'"; query(query); } public static void query(String query) { try { BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService(); QueryJobConfiguration queryConfig = QueryJobConfiguration.of(query); TableResult results = bigquery.query(queryConfig); results .iterateAll() .forEach(row -> row.forEach(val -> System.out.printf("%s,", val.toString()))); System.out.println("Query performed successfully."); } catch (BigQueryException | InterruptedException e) { System.out.println("Query not performed \n" + e.toString()); } }
使用的依赖版本:
implementation platform('com.google.cloud:libraries-bom:26.1.4') implementation group: 'com.google.cloud', name: 'google-cloud-bigquery', version: '2.18.2'
错误原因
这个错误是Gson版本冲突导致的:
JsonParser.parseString()方法是在Gson 2.8.6版本才新增的- 项目中可能引入了更低版本的Gson依赖,或者通过其他间接依赖引入了旧版Gson,导致运行时找不到该方法
解决方案
方案1:通过BOM统一管理依赖版本
你已经引入了Google Cloud Libraries BOM,建议移除google-cloud-bigquery的显式版本号,让BOM自动管理所有Google Cloud客户端的依赖版本,从根源避免版本冲突:
implementation platform('com.google.cloud:libraries-bom:26.1.4') implementation group: 'com.google.cloud', name: 'google-cloud-bigquery'
方案2:强制指定兼容的Gson版本
如果方案1无效,可以在依赖中显式指定符合要求的Gson版本(最低2.8.6,推荐使用较新版本):
implementation group: 'com.google.code.gson', name: 'gson', version: '2.10.1'
方案3:排查并排除旧版Gson依赖
通过构建工具命令查看依赖树,找到引入旧版Gson的依赖,然后排除它:
- Gradle查看依赖树:
./gradlew dependencies - 找到对应依赖后,添加排除配置:
implementation('xxx:xxx:xxx') { exclude group: 'com.google.code.gson', module: 'gson' }
内容的提问来源于stack exchange,提问作者Rahul Goti
相关产品推荐
相关产品推荐

