名称只包含数字的变量(kotlin/android)



我需要创建与API响应完全相同的变量,以便在其中保存数据。这就是为什么我要创建这样的变量:

val 50: String
val 100: String

但是正如你所知道的,我不能这样做,那么我如何创建名称只包含数字的变量呢?

如果您使用Gson库将Json api转换为kotlin Data类,请添加相同的@SerializedName("key_api")注释

import com.google.gson.annotations.SerializedName
data class YourResponse {
@SerializedName("50")
val firstVariableName: String? = null,
@SerializedName("100")
val secondVariableName: String? = null
}

有了这个注释,Gson将用你的变量名映射Json的键。

你可以用'

// define
val `50`: String 
val `100`: String
// access
`50` = "123"
`100` = "456"
println("${`50`}${`100`}")

如果您使用RetrofitGson,您应该使用@SerializedName查看此

最新更新