首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从kotlin中的资产解析json文件?

如何从kotlin中的资产解析json文件?
EN

Stack Overflow用户
提问于 2022-11-14 16:15:28
回答 1查看 49关注 0票数 0

如何在kotlin中解析json文件。在互联网上有很多解决方案,但是它们都是相同的,但是我无法在kotlin中找到解析我的json文件的方法。

我的json文件

代码语言:javascript
复制
{
    "A": [
        {
            "collocation": "above average",
            "meaning": "more than average, esp. in amount, age, height, weight etc. "
        },
        {
            "collocation": "absolutely necessary",
            "meaning": "totally or completely necessary"
        },
        {
            "collocation": "abuse drugs",
            "meaning": "to use drugs in a way that's harmful to yourself or others"
        },
        {
            "collocation": "abuse of power",
            "meaning": "the harmful or unethical use of power"
        }
    ],
    "B": [
        {
            "collocation": "back pay",
            "meaning": "money a worker earned in the past but hasn't been paid yet  "
        },
        {
            "collocation": "back road",
            "meaning": "a small country road "
        },
        {
            "collocation": "back street",
            "meaning": "a street in a town or city that's away from major roads or central areas"
        },
        {
            "collocation": "back taxes",
            "meaning": "taxes that weren't paid when they were due"
        },
        {
            "collocation": "bad breath",
            "meaning": "breath that doesn't smell nice"
        }],

这样就可以达到字母W

我想用信来分析它们。

我的数据类

代码语言:javascript
复制
data class Collocations(

    val tag:String,
    val collocation: List<Collocation>

)
data class Collocation(
    val collocation: String,
    val meaning: String
)

但我认为这些数据类在我看来是不正确的,或者是无效的。

EN

回答 1

Stack Overflow用户

发布于 2022-11-14 17:26:56

您应该只需要这里提供的Collocation类。然后顶层对象可以是一个Map<String, List<Collocation>>,因此字母可以是动态键。

使用Kotlinx序列化,它可以如下所示:

代码语言:javascript
复制
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json

@Serializable
data class Collocation(
    val collocation: String,
    val meaning: String,
)

fun main() {
    val json: String = TODO("get your JSON string here")
    val collocations = Json.decodeFromString<Map<String, List<Collocation>>>(json)

    val collocationsForA = collocations["A"]
    println(collocationsForA)
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74434688

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档