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

Kotlin中如何将文件中的对象字符串反序列化为原对象?

如何将本地JSON文件反序列化为DrinkItem对象?

我已将标注@Serializable的DrinkItem对象写入本地文件,现在希望读取文件中的JSON字符串,并将其转换回可正常使用的DrinkItem对象。请问有可用的函数或库来实现该反序列化操作?

DrinkItem类代码

@Serializable
class DrinkItem {
    @SerializedName("strAlcoholic")
    val alcoholic: String? = null
    @SerializedName("strIngredient1")
    val ingredient1: String? = null
    @SerializedName("strIngredient10")
    val ingredient10: String? = null
    @SerializedName("strIngredient11")
    val ingredient11: String? = null
    @SerializedName("strIngredient12")
    val ingredient12: String? = null
    @SerializedName("strIngredient13")
    val ingredient13: String? = null
    @SerializedName("strIngredient14")
    val ingredient14: String? = null
    @SerializedName("strIngredient15")
    val ingredient15: String? = null
    @SerializedName("strIngredient2")
    val ingredient2: String? = null
    @SerializedName("strIngredient3")
    val ingredient3: String? = null
    @SerializedName("strIngredient4")
    val ingredient4: String? = null
    @SerializedName("strIngredient5")
    val ingredient5: String? = null
    @SerializedName("strIngredient6")
    val ingredient6: String? = null
    @SerializedName("strIngredient7")
    val ingredient7: String? = null
    @SerializedName("strIngredient8")
    val ingredient8: String? = null
    @SerializedName("strIngredient9")
    val ingredient9: String? = null
    @SerializedName("strInstructions")
    val instructions: String? = null
    @SerializedName("strMeasure1")
    val measurement1: String? = null
    @SerializedName("strMeasure10")
    val measurement10: String? = null
    @SerializedName("strMeasure11")
    val measurement11: String? = null
    @SerializedName("strMeasure12")
    val measurement12: String? = null
    @SerializedName("strMeasure13")
    val measurement13: String? = null
    @SerializedName("strMeasure14")
    val measurement14: String? = null
    @SerializedName("strMeasure15")
    val measurement15: String? = null
    @SerializedName("strMeasure2")
    val measurement2: String? = null
    @SerializedName("strMeasure3")
    val measurement3: String? = null
    @SerializedName("strMeasure4")
    val measurement4: String? = null
    @SerializedName("strMeasure5")
    val measurement5: String? = null
    @SerializedName("strMeasure6")
    val measurement6: String? = null
    @SerializedName("strMeasure7")
    val measurement7: String? = null
    @SerializedName("strMeasure8")
    val measurement8: String? = null
    @SerializedName("strMeasure9")
    val measurement9: String? = null
    @SerializedName("strDrink")
    val name: String? = null
    @SerializedName("strDrinkThumb")
    val thumbnail: String? = null
}

写入文件函数

private fun writeToFile(fileName: String, byteArray: ByteArray){
    val lineSeparator: String = System.getProperty("line.separator") as String
    val path = context!!.filesDir
    val directory = File(path, "LET")
    directory.mkdirs()
    val file = File(directory, fileName)
    FileOutputStream(file, true).use {
        it.write(byteArray)
        it.write(lineSeparator.toByteArray())
    }
}

生成的JSON字符串

{"alcoholic":"Alcoholic","ingredient1":"Apricot brandy","ingredient2":"Triple sec","ingredient3":"Lime","ingredient4":"Lime","instructions":"Shake all ingredients (except lime wedge) with ice and strain into a cocktail glass. Add the wedge of lime and serve.","measurement1":"1 oz ","measurement2":"1 oz ","measurement3":"Juice of 1 ","measurement4":"1 ","name":"After Dinner Cocktail","thumbnail":"https://www.thecocktaildb.com/images/media/drink/vtytxq1483387578.jpg"}

可用的反序列化方案

方案1:使用Kotlinx Serialization(推荐,适配类上的@Serializable注解)

你的DrinkItem类已经标注了Kotlinx Serialization的@Serializable注解,只需补充依赖并实现读取逻辑:

1. 添加依赖

根据你的Gradle类型选择配置:

// Gradle Kotlin DSL
plugins {
    kotlin("plugin.serialization") version "你的Kotlin版本号"
}

dependencies {
    implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.0")
}
// Groovy DSL
plugins {
    id 'org.jetbrains.kotlin.plugin.serialization' version '你的Kotlin版本号'
}

dependencies {
    implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.0'
}

2. 读取反序列化函数

private fun readDrinkFromFile(fileName: String): DrinkItem? {
    val path = context!!.filesDir
    val directory = File(path, "LET")
    val file = File(directory, fileName)
    
    return try {
        val jsonContent = file.readText()
        // 处理写入时添加的换行,取非空的第一行JSON
        val targetJson = jsonContent.lines().firstOrNull { it.isNotBlank() } ?: return null
        Json.decodeFromString<DrinkItem>(targetJson)
    } catch (e: Exception) {
        e.printStackTrace()
        null
    }
}

方案2:使用Gson(适配类上的@SerializedName注解)

你的类同时使用了Gson的@SerializedName注解,也可以用Gson完成反序列化:

1. 添加依赖

// Gradle Kotlin DSL
implementation("com.google.code.gson:gson:2.10.1")
// Groovy DSL
implementation 'com.google.code.gson:gson:2.10.1'

2. 读取反序列化函数

private fun readDrinkFromFileWithGson(fileName: String): DrinkItem? {
    val path = context!!.filesDir
    val directory = File(path, "LET")
    val file = File(directory, fileName)
    
    return try {
        val jsonContent = file.readText()
        val targetJson = jsonContent.lines().firstOrNull { it.isNotBlank() } ?: return null
        Gson().fromJson(targetJson, DrinkItem::class.java)
    } catch (e: Exception) {
        e.printStackTrace()
        null
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 14:55:15