簡體   English   中英

在 API 響應 Model 在 Kotlin ZE84E30B9390CDB464DB6DB2C9ABZ78 中調用輔助構造函數

[英]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 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字段是 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM