Kotlinx 序列化 - 如何为未知字段名称写入数据 class

Kotlinx serialization - How to write a data class for an unknown field name

我尝试为来自 public API 的以下 JSON 响应写入数据 class:

{
  "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
    }  
  }
}

我的数据 class 看起来像:

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

在数据 class“结果”中,我声明为“asset_name”的字段名称对于每个条目都是不同的。数据 class 必须是什么样子?有人可以帮忙吗?

Resultclass不需要。您的数据 classes 应如下所示:

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