如何在Android项目Kotlin/Java中读取credentials.json(非Assets类Firebase方式)
实现类似Firebase读取
google-services.json的方式读取credentials.json Firebase的google-services.json是通过官方Gradle插件在构建阶段解析,并将配置注入到BuildConfig或资源中,实现运行时无路径依赖的访问。以下是针对credentials.json的实现方案:
方案1:通过Gradle构建脚本生成BuildConfig字段
这种方式会在构建时解析credentials.json,将所需字段写入BuildConfig,运行时直接通过BuildConfig访问,和Firebase的思路一致。
步骤1:在app模块的build.gradle.kts中添加解析逻辑
在android块内添加以下代码:
android { // 其他配置... defaultConfig { // 其他配置... buildConfigField("String", "CREDENTIALS_JSON", readCredentialsJson()) } } fun readCredentialsJson(): String { val credentialsFile = file("credentials.json") require(credentialsFile.exists()) { "credentials.json not found in app module root" } val content = credentialsFile.readText(Charsets.UTF_8) // 转义双引号,避免BuildConfig语法错误 return "\"${content.replace("\"", "\\\"")}\"" }
步骤2:同步Gradle后,运行时访问
在Kotlin代码中直接读取:
val credentialsJson = BuildConfig.CREDENTIALS_JSON // 解析JSON(示例用Gson) val credentialModel = Gson().fromJson(credentialsJson, CredentialModel::class.java)
方案2:通过Gradle将JSON内容生成raw资源文件
如果需要保留JSON的原始格式,也可以在构建时将credentials.json复制到res/raw目录,运行时通过资源ID访问:
步骤1:在app模块的build.gradle.kts添加复制任务
tasks.register<Copy>("copyCredentialsToRaw") { val credentialsFile = file("credentials.json") from(credentialsFile) into(layout.buildDirectory.dir("generated/res/raw/${android.defaultConfig.applicationId}")) rename { "credentials_raw.json" } dependsOn("preBuild") } android { // 其他配置... sourceSets { getByName("main") { res.srcDir(layout.buildDirectory.dir("generated/res/raw/${android.defaultConfig.applicationId}")) } } tasks.named("processDebugResources") { dependsOn("copyCredentialsToRaw") } tasks.named("processReleaseResources") { dependsOn("copyCredentialsToRaw") } }
步骤2:运行时读取资源
val inputStream = resources.openRawResource(R.raw.credentials_raw) val credentialsJson = inputStream.bufferedReader().use { it.readText() } // 后续解析逻辑同上
关键说明
- 两种方案都是构建阶段处理文件,避免运行时依赖文件路径,和Firebase的
google-services.json处理逻辑一致; - 确保
credentials.json放在app模块的根目录(即projectname/app/下),和google-services.json的位置相同; - 若JSON内容包含敏感信息,注意在版本控制中忽略该文件(添加到
.gitignore),避免泄露。
内容的提问来源于stack exchange,提问作者Shashwat Samadhiya
相关产品推荐
相关产品推荐

