Reputation: 1139
I'm making a quiz app in Kotlin where there is a question with between 2 and 5 answer options together with scores. So there is the question number, question, answers and points for each answer. I have made the app in flutter where I used Map with one key (question number: question) and another key (answer option: score). The answer used a list for the multiple options. What would be the best way to do it in Kotlin?
Flutter code
{
'Question 1': 'Do you ...?',
'answers': [
{'text': 'Not at all', 'score': 0},
{'text': 'Partly', 'score': 50},
{'text': 'Mostly', 'score': 280},
{'text': 'Completely', 'score': 500},
],
},
Upvotes: 0
Views: 2612
Reputation: 1179
With thanks to Lena Bru for the original answer, which unfortunately had a few bugs in it. This should be a working version that addresses your question:
data classes:
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 data:
val json = """
[
{
"Question": "Why?",
"answers": [
{
"text": "Because I said so",
"score": 10
},
{
"text": "Dunno",
"score": 20
}
]
}
]
"""
And finally, parsing the json and displaying it:
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}")
}
}
The main differences with the previous answer:
Hope this helps and is still relevant.
Upvotes: 1
Reputation: 13937
data class Answer(@SerializedName("text") val text: String = "", @SerializedName("score") score: Int = 0)
data class Question(@SerializedName("Question") val questionText: String = "", answers: List<Answer> = listOf())
In my opinion your json structure is not good, because you have a number inside the question key, i.e "Question 1"
I would structure it the following way:
json = [
{ "Question": "why is blabla a blabla?",
"answers": ["because I said so", "who knows?", "It doesnt matter"]
},
{ "Question": "Is this a second question because it is an array of questions?",
"answers": ["Yes", "No", "White", "Black"]
}
]
When you put that json through gson for example (the common google json parser)
val questions: List<Question> = gson.fromJson(json,TypeToken<List<Question>(){}.type)
questions.forEach { question ->
Log.d("TAG","The question is:${question.questionText}"
Log.d("TAG","The answers are: ${question.answers.contentToString()}"
}
Upvotes: 1