[英]Calling Secondary Constructor in API response Model in Kotlin Android
我的 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
}
我正在使用下面的数据 Class 来解析上面的 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
model 类的不同构造函数,这样它不会给出这样的错误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
排除策略。
您的 JSON 中的body
字段是 object 并且应该 map 在您的项目中定义为 ZA8CFDE6331BD59EB2666F8911ZB4 为此,您可以使用如下 class header :
data class Body(val count: Int, val sender: String)
然后,您的Notification
class header 将有一个Body
字段来捕获您的 JSON 响应的该部分,如下所示:
data class Notification(val body: Body, val inserted_at: String, val type: Int)
我通常使用 Gson 来反序列化 Retrofit 响应。 它工作得很好,而且很容易定制。 让我知道是否需要澄清。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.