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

如何在Kotlin中解析Assets目录下的分类JSON文件?

Kotlin解析A-W分类的搭配短语JSON文件

首先明确你的JSON结构示例(符合A到W字母键对应搭配数组的格式):

{
  "A": [
    {"collocation": "account for", "meaning": "解释;占比"},
    {"collocation": "adapt to", "meaning": "适应"}
  ],
  "B": [
    {"collocation": "break down", "meaning": "分解;出故障"}
  ],
  // ... 后续字母C到W的结构以此类推
}

问题根源:旧数据类的不合理性

之前定义的Collocations类大概率是硬编码了A到W的每个属性(比如val A: List<Collocation>?),这种写法不仅冗余,还无法灵活适配JSON结构的变动,改用动态键的Map才是正确思路。

解决方案:用Map替代硬编码数据类

下面提供两种主流Kotlin JSON解析库的实现方案:

方案1:使用Gson

  1. 添加Gradle依赖
dependencies {
    implementation("com.google.code.gson:gson:2.10.1")
}
  1. 定义基础数据类
data class Collocation(
    val collocation: String,
    val meaning: String
)
  1. 解析与分类处理
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

// 读取JSON文件内容到字符串(实际项目中可通过File或Assets读取)
val jsonContent = """你的JSON内容"""

val gson = Gson()
// 借助TypeToken指定泛型类型
val collocationType = object : TypeToken<Map<String, List<Collocation>>>() {}.type
val collocationMap: Map<String, List<Collocation>> = gson.fromJson(jsonContent, collocationType)

// 按字母分类遍历处理
collocationMap.forEach { (letter, items) ->
    println("=== 字母 $letter 下的搭配短语 ===")
    items.forEach { item ->
        println("搭配:${item.collocation} | 含义:${item.meaning}")
    }
}

方案2:使用kotlinx.serialization(Kotlin官方库)

  1. 添加Gradle配置与依赖
plugins {
    kotlin("plugin.serialization") version "1.9.20"
}

dependencies {
    implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.0")
}
  1. 定义序列化数据类
import kotlinx.serialization.Serializable

@Serializable
data class Collocation(
    val collocation: String,
    val meaning: String
)
  1. 解析与分类处理
import kotlinx.serialization.json.Json
import kotlinx.serialization.decodeFromString

val jsonContent = """你的JSON内容"""

// 直接解码为Map<String, List<Collocation>>
val collocationMap: Map<String, List<Collocation>> = Json.decodeFromString(jsonContent)

// 分类处理逻辑同Gson示例
collocationMap.forEach { (letter, items) ->
    println("=== 字母 $letter 下的搭配短语 ===")
    items.forEach { item ->
        println("${item.collocation}: ${item.meaning}")
    }
}

关键优势

  • 无需硬编码A到W的每个字母属性,完全适配动态键结构
  • 代码简洁易维护,后续JSON新增字母时无需修改数据类
  • 两种方案均支持按字母键快速检索对应搭配组

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 13:40:26