I'm using Kotlin Serialization to parse the JSON data. I just want to parse the first type (eg. grass) to my data class. How do I do that?
@Serializable
data class PokemonResponse(
val id: Int,
val name: String,
val type: String,
val weight: Double,
val height: Double
)
JSON
{
"height": 7,
"id": 1,
"name": "bulbasaur",
"types": [
{
"slot": 1,
"type": {
"name": "grass",
"url": "https://pokeapi.co/api/v2/type/12/"
}
},
{
"slot": 2,
"type": {
"name": "poison",
"url": "https://pokeapi.co/api/v2/type/4/"
}
}
],
"weight": 69
}
The correct representation of that JSON is the following:
@Serializable
data class PokemonResponse(
val id: Int,
val name: String,
val types: List<TypeSlot>,
val weight: Double,
val height: Double
)
@Serializable
data class TypeSlot(
val slot: Integer,
val type: Type,
)
@Serializable
data class Type(
val name: String,
val url: String,
)
To parse the first type you see you would access it like this: pokemonResponse.types[0].type.name
given that pokemonResponse is of type PokemonResponse. Gotta catch'em all!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.