我正在尝试解析主要是这样构造的API响应:
{
"ApiFunc1":{
"SomeData1":"SomeValue1",
"SomeData2":"SomeValue2",
"SomeData3":"SomeValue3"
}
}
{
"ApiFunc2":{
"SomeData4":"SomeValue4",
"SomeData5":"SomeValue5",
"SomeData6":"SomeValue6"
}
}
.
.
.
我创建了一个基类,如下所示:
class Model_BaseResponse<TResponse> : Serializable {
@SerializedName("ErrorMessage")
var errorMessage: String? = null
@SerializedName("value")
var data: TResponse? = null
}
每个ApiFunc返回不同的数据。我想创建一个基类,可以在子类中设置
data: TResponse
的@SerializedName(“ApiFunc1”)或@SerializedName(“ApiFunc2”)。有什么办法吗?我会定期进行定义@SerializedName("value")
var data: TResponse? = null
在每个 child 类。只是对此感到好奇。预先感谢您的任何想法。
最佳答案
像SerializedData
这样的注释要求其参数为编译时常量。看看Kotlin中的“编译时常数”意味着什么:
Properties the value of which is known at compile time can be marked as compile time constants using the const modifier. Such properties need to fulfil the following requirements:
- Top-level or member of an object
- Initialized with a value of type String or a primitive type
- No custom getter
Such properties can be used in annotations:
const val SUBSYSTEM_DEPRECATED: String = "This subsystem is deprecated" @Deprecated(SUBSYSTEM_DEPRECATED) fun foo() { ... }
我相信您的用例不能满足“对象的顶级或成员”的第一个要求。
关于json - 从Kotlin的子类获取SerializedName参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51069786/