gpt4 book ai didi

kotlin - 使用多个键和值进行映射

转载 作者:行者123 更新时间:2023-12-02 13:19:13 24 4
gpt4 key购买 nike

我在Kotlin制作了一个测验应用程序,那里有一个2到5个答案选项以及分数的问题。因此,有问题编号,问题,答案和每个答案的要点。我使该应用程序变得扑朔迷离,在其中我通过一个键(问题编号:问题)和另一个键(答案选项:得分)使用了Map。答案使用了多个选项的列表。在Kotlin中最好的方法是什么?

颤动代码

{
'Question 1': 'Do you ...?',
'answers': [
{'text': 'Not at all', 'score': 0},
{'text': 'Partly', 'score': 50},
{'text': 'Mostly', 'score': 280},
{'text': 'Completely', 'score': 500},
],
},

最佳答案

感谢Lena Bru的original回答,不幸的是其中包含一些错误。这应该是可以解决您问题的工作版本:

数据类别:

data class Answer(
@SerializedName("text") val text: String = "",
@SerializedName("score") val score: Int = 0
)

data class Question(
@SerializedName("Question") val questionText: String = "",
val answers: List<Answer> = listOf()
)

json数据:

val json = """
[
{
"Question": "Why?",
"answers": [
{
"text": "Because I said so",
"score": 10
},
{
"text": "Dunno",
"score": 20
}
]
}
]
"""

最后,解析并显示json:

val gson = Gson()
val questions: List<Question> = gson.fromJson(json, object : TypeToken<List<Question?>?>() {}.type)


questions.forEach { question ->
println("The question is: ${question.questionText}")
println("The answers are:")
question.answers.forEach {answer ->
println(" Text: ${answer.text}, score: ${answer.score}")
}
}

与先前答案的主要区别:
  • 更改了json以匹配数据类
  • json现在是字符串
  • 固定的显示代码

  • 希望这会有所帮助并且仍然有意义。

    关于kotlin - 使用多个键和值进行映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60356921/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com