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

2.3k views Asked by At

I try to write a data class for the following JSON response from a public API:

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

My data class looks like:

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

In the data class "Result" the field name, that I declared as "asset_name" is different for every entry. How does the data class have to look like? Can someone help please?

1

There are 1 answers

0
Михаил Нафталь On BEST ANSWER

There is no need in Result class. Your data classes should look like this:

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