1

我尝试为来自公共 API 的以下 JSON 响应编写数据类:

{
  "error": [],
  "result": {
    "AAVE": {
      "aclass": "currency",
      "altname": "AAVE",
      "decimals": 10,
      "display_decimals": 5
    },
    "ADA": {
      "aclass": "currency",
      "altname": "ADA",
      "decimals": 8,
      "display_decimals": 6
    },
    "ALGO": {
      "aclass": "currency",
      "altname": "ALGO",
      "decimals": 8,
      "display_decimals": 5
    },
    "ANT": {
      "aclass": "currency",
      "altname": "ANT",
      "decimals": 10,
      "display_decimals": 5
    }  
  }
}

我的数据类看起来像:

@Serializable
data class AssetInfo (
        @SerialName("error")
        val error: List<String>?,

        @SerialName("result")
        val result: Result,

)

@Serializable
data class Result(
/*
Here is the problem, because the field "asset_name" does not exist.
*/
        @SerialName("asset_name")
        val asset_name: Asset,

)

@Serializable
data class Asset(
        @SerialName("altname")
        val altname : String,

        @SerialName("aclass")
        val aclass  : String,

        @SerialName("decimals")
        val decimals  : String,

        @SerialName("display_decimals")
        val display_decimals  : String,
)

在数据类“Result”中,我声明为“asset_name”的字段名称对于每个条目都是不同的。数据类的外观如何?有人可以帮忙吗?

4

1 回答 1

0

上课没必要Result。您的数据类应如下所示:

@Serializable
data class AssetInfo(
    @SerialName("error")
    val error: List<String>?,

    @SerialName("result")
    val result: Map<String, Asset>
)

@Serializable
data class Asset(
    @SerialName("altname")
    val altname: String,

    @SerialName("aclass")
    val aclass: String,

    @SerialName("decimals")
    val decimals: Int,

    @SerialName("display_decimals")
    val display_decimals: Int
)
于 2021-04-16T09:46:14.367 回答