【发布时间】:2020-05-07 08:24:47
【问题描述】:
我的 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这样的错误
我应该如何改进我的代码来解析响应?
感谢任何帮助!
【问题讨论】:
-
bodyJSON 响应中的字段是第一个对象和第二个字符串。这可能是您遇到错误的情况。 -
是的,我知道错误,这是我的问题,即如何改造我的数据类以捕获这两种类型,这就是为什么我也引入了辅助构造函数
-
你使用哪个库进行反序列化?
-
我只是在手动使用改造和反序列化使用数据类
标签: android json api kotlin data-class