首页 > 解决方案 > 如何在 kotlin 中转换这个复杂的 json

问题描述

我想将此 Json 文件转换为 kotlin :

   {
    "results": {
        "ALL": {
            "currencyName": "Albanian Lek",
            "currencySymbol": "Lek",
            "id": "ALL"
        },
        "XCD": {
            "currencyName": "East Caribbean Dollar",
            "currencySymbol": "$",
            "id": "XCD"
        }
    }
}


interface Api {

    @GET(ApiEndPoints.GET_CURRENCIES)
    suspend fun getCurrencies(
        @Query(Constants.API_KEY)
        countryCode: String = ApiEndPoints.API_KEY,
        @Query(Constants.FROM_TO)
        apiKey:String = "USD_USD",
        @Query("compact")
        compact:String = "ultra"
    ):CurrencyResults

}

模型:

data class CurrencyResults(
    val results: Map<String, Currency>
)

data class Currency(
    val currencyName: String,
    val currencySymbol: String,
    val id: String,
)

查看型号:

 init {
        viewModelScope.launch {
            //Should get result here 

        }
    }

它的 JSON 包含超过 100 个对象,如上面的这个片段!我不能在这里得到它当我试图将它转换为 kotlin 时,我得到错误或 null 或者必须编写超过 100 个类来检测所有 json 对象!我想将其转换为 Currency 模型类来保存名称、符号和 id !我能做些什么 ?

标签: androidjsonkotlinarraylist

解决方案


关于什么:

data class CurrencyResults(
    val results: Map<String, Currency>
)

data class Currency(
    val currencyName: String,
    val currencySymbol: String,
    val id: String,
)

推荐阅读