在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)

}

但这项艰巨的工作会产生类似于-Expected String , got object的解析错误

我的Api呼叫看起来像-

@GET("notifications")
suspend fun getNotifications(
@HeaderMap headers: HashMap<String, String>
): Response<List<Notification>>

主要目标是如何重构代码,以便在不同的情况下调用Notification模型类的不同构造函数,从而使其不会给出此类错误expecting string, got objectexpecting 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排除策略。

JSON中的body字段是一个对象,应该映射到项目中定义的对象。为此,您可以有一个类似以下的类头:
data class Body(val count: Int, val sender: String)

然后,Notification类头将有一个Body字段来捕获JSON响应的这一部分,如下所示:

data class Notification(val body: Body, val inserted_at: String, val type: Int)

我通常使用Gson来反序列化改装响应。它工作得非常好,而且很容易定制。如果有什么需要澄清,请告诉我。

最新更新