首页 > 解决方案 > 如何使用 Kotlin 序列化解析 JSON 对象列表中的第一个属性?

问题描述

我正在使用 Kotlin 序列化来解析 JSON 数据。我只想将第一种类型(例如草)解析为我的数据类。我怎么做?

@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
}

标签: androidjsonparsingkotlin

解决方案


该 JSON 的正确表示如下:

@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,
)

要解析您看到的第一个类型,您可以像这样访问它: pokemonResponse.types[0].type.name假设 pokemonResponse 是 PokemonResponse 类型。需要把他们全都抓到!


推荐阅读