2

我正在使用 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",
}
4

1 回答 1

3

正如@eric-cochran 指出的那样,您实际上并不需要一个新的数据类来表示这一点。它最终会成为一个地图,你会像这样使用它:

@GET("data/getlist")
fun getVariableData(): Single<Map<String, String>>
于 2018-02-16T07:36:58.620 回答