我正在使用 Retrofit 2 和 Moshi 从端点读取和解析 JSON。我的改造实例是这样定义的:
val retrofit: Retrofit = Retrofit.Builder()
.baseUrl("https://myendpoint.com")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(MoshiConverterFactory.create())
.build()
我正在使用 Kotlin 数据类将信息存储在模型中:
@GET("data/getlist")
fun getData(): Single<Data>
数据类:
data class Data(val Response : String,
val Message : String,
val BaseImageUrl : String)
现在,因为 JSON 是这样格式化的,所以解析 JSON 并且填充模型就好了:
{
"Response": "Success",
"Message": "Api successfully returned",
"BaseImageUrl": "https://www.endpoint.com/image/xxx.jpg",
}
这是因为对象与模型 1:1 映射。所以在上面的例子中,“Response”键映射到Data类中的“Response”变量名。
我的问题是:如果键都是可变的怎么办?您如何在 Kotlin 数据类中表示这一点?
要解析的示例 JSON 文件:
{
"RandomX": "xxxxxx",
"RandomY": "yyyyyy",
"RandomZ": "zzzzzz",
}