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

Kotlin读取Assets目录JSON时遇JSONObject转换、文件找不到报错如何解决

报错解决方法

错误1:Failed to open file, no such file or directory 修复方案

  • 确认JSON文件存放路径为Android项目src/main/assets目录,若文件放在assets的子目录下,取值时需要补全相对路径,例:assets.open("sub/user_data.json")
  • 校验K.json.jsonFileName取值与实际文件名完全匹配,Android assets文件名大小写敏感,不可多/少文件后缀
  • 优化空安全逻辑,避免读取失败返回null时触发空指针崩溃:
val jsonStr = getJSONFromAssets() ?: run {
    // 此处补充文件读取失败的业务逻辑,如提示用户等
    return@对应作用域
}
val obj = JSONObject(jsonStr)

错误2:Value 1 at user_id of type java.lang.String cannot be converted to JSONObject 修复方案

该报错由类型不匹配、key拼写错误两类问题导致,修复步骤如下:

  • 修正user_id取值方法:JSON中user_id是字符串类型,不可用getJSONObject读取,改为getString:
// 错误写法
val userArray = obj.getJSONObject("user_id")
// 正确写法
val userId = obj.getString("user_id")
  • 修正数组key拼写:你提供的JSON示例中数组key为acounts,但数据类UserModelClass中定义的字段名为accounts,需保证二者完全一致,要么修改JSON中的key为accounts,要么解析时使用acounts作为取值key
  • 补充完整数组解析逻辑示例:
val accountJsonArray = obj.getJSONArray("accounts") // 和JSON中key保持一致
val accountList = mutableListOf<AccountsList>()
// 遍历数组
for (index in 0 until accountJsonArray.length()) {
    val accountItem = accountJsonArray.getJSONObject(index)
    val accountsList = AccountsList(
        id = accountItem.getString("id"),
        accountNumber = accountItem.getString("AccountNumber"),
        amount = accountItem.getString("amount"),
        currency = accountItem.getString("currency"),
        // 补充transactions字段的解析逻辑
    )
    accountList.add(accountsList)
}
// 组装成最终数据类
val userData = UserModelClass(user_id = userId, accounts = accountList)

额外注意:你提供的JSON示例不完整,transactions字段未写完全,整个JSON结构也缺少对应的闭合括号,需先补全合法的JSON结构再解析,否则会触发格式异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 21:15:05