我在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的原始回答,不幸的是其中包含一些错误。这应该是可以解决您问题的工作版本:
数据类别:
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}")
}
}
与先前答案的主要区别:
希望这会有所帮助并且仍然有意义。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句