You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio添加Retrofit依赖与Gson转换器时Gradle构建报错

解决Gradle build.kt中添加Retrofit依赖时的"Unexpected tokens"错误

正确的依赖配置写法(Kotlin DSL)

确保在build.gradle.kts的dependencies块中使用标准Kotlin语法添加Retrofit和Gson转换器:

dependencies {
    // Retrofit核心依赖
    implementation("com.squareup.retrofit2:retrofit:2.9.0")
    // Gson转换器依赖
    implementation("com.squareup.retrofit2:converter-gson:2.9.0")
}

常见错误原因及修复

  1. 混用Groovy语法
    若习惯了Groovy版build.gradle的写法,用单引号'包裹依赖坐标或者省略括号(比如implementation 'com.squareup.retrofit2:retrofit:2.9.0'),这在Kotlin DSL中会触发语法错误。必须改成Kotlin要求的双引号+括号格式:implementation("xxx")。

  2. 语法格式错误
    检查是否存在漏写括号、逗号错位,或者同一行多表达式未加分号的情况。比如同一行声明多个依赖时,必须用分号分隔:

    // 错误写法
    implementation("xxx") implementation("yyy")
    // 正确写法
    implementation("xxx"); implementation("yyy")
    // 更推荐的写法:每行一个依赖
    implementation("xxx")
    implementation("yyy")
    
  3. 依赖坐标拼写错误
    检查依赖的groupId、artifactId或版本号是否拼写错误,比如把converter-gson写成converter-gsonn,错误的坐标会让Gradle解析时抛出语法类异常。

验证步骤

写完依赖后,点击Android Studio右上角的「Sync Now」按钮同步Gradle,若仍有报错,检查文件其他区域是否存在未闭合的代码块或其他语法问题。

内容的提问来源于stack exchange,提问作者Ankit Vishwakarma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 11:55:58