android - 在 Kotlin Android 的 API 响应模型中调用辅助构造函数
问题描述
我的 JSON 响应看起来像 -
{
"body": {
"count": 4,
"sender": "margarete20181570"
},
"inserted_at": "2020-05-07T05:48:14.465Z",
"type": 1
},
{
"body": "savanna19562530 hit the SOS button!",
"inserted_at": "2020-05-06T09:17:36.658Z",
"type": 2
}
我正在使用下面的数据类来解析上面的 JSON,这里有什么问题!
data class Notification(val body: String, val inserted_at: String, val type: Int) {
constructor(
msgBody: MessageNotification,
inserted_at: String,
type: Int
) : this(msgBody.sender + "Sent you " + msgBody.count + "Messages", inserted_at, type)
}
但是这个dosent工作它给出了解析错误,比如 -Expected String , got object
我的 Api 调用看起来像 -
@GET("notifications")
suspend fun getNotifications(
@HeaderMap headers: HashMap<String, String>
): Response<List<Notification>>
主要目标是如何重构代码,以便Notification
在不同情况下调用模型类的不同构造函数,从而不会给出这样的错误expecting string, got object
或expecting object got string
我应该如何改进我的代码来解析响应?
任何帮助表示赞赏!
解决方案
由于您要手动反序列化 JSON,这可能是您可以尝试的解决方案
data class Body(val count: Int, val sender: String)
data class Notification(val body: Any, val insertedAt: String, val type: Int)
现在,解析 JSON 响应
val jsonResponse = JSONArray(/*JSON response string*/) // I am guessing this is an array
(0 until jsonResponse.length()).forEach {
val jsonObj = jsonResponse.getJSONObject(it)
val jsonBody = jsonObj.get("body")
if (jsonBody is String) {
// Body field is a String instance
val notification = Notification(
body = jsonBody.toString(),
insertedAt = jsonObj.getString("inserted_at"),
type = jsonObj.getInt("type")
)
// do something
} else {
// Body field is a object
val jsonBodyObj = jsonObj.getJSONObject("body")
val body = Body(
count = jsonBodyObj.getInt("count"),
sender = jsonBodyObj.getString("sender")
)
val notification = Notification(
body = body,
insertedAt = jsonObj.getString("inserted_at"),
type = jsonObj.getInt("type")
)
// do something
}
}
我希望这有助于或至少让您了解如何解决问题。您还可以检查Gson
排除策略。