【发布时间】:2020-01-12 13:11:25
【问题描述】:
我正在尝试使用 Codable 解析来自后端的一些 JSON 响应,但总是出现类型不匹配。
我在使用 Codable 之前从未遇到过这个问题。
这是我的 JSON:
{
"success": true,
"result": {
"uuid": "ed26b73f-9661-44e0-9975-d841bc533849",
"update_time": "1568035713",
"category_uuid": "b36c1549-c4c9-11e9-8fcd-9151e37ecd87",
"title": "optionaltask",
"description": "",
"reminder_time": 1212121212,
"same_day": 0,
"before_day": 0,
"three_days": 0,
"by_email": 0,
"by_sms": 0,
"by_notification": 0,
"mp3_time": null,
"file_name": null,
"file_link": null,
"status": "0"
},
"error": null
}
这是我的 Codable 结构:
struct RespElement: Codable {
let success: Bool
let result: Task
let error: String?
}
class Task: Object, Codable {
var uuid, updateTime, categoryUUID, title: String
var resultDescription: String?
var sameDay, beforeDay, threeDays: Int
var bySMS, byNotification: Int
var byEmail: Int
var reminderTime: Int
var mp3Time: Int?
var fileName, fileLink: String?
var status: String
enum CodingKeys: String, CodingKey {
case uuid
case updateTime = "update_time"
case categoryUUID = "category_uuid"
case title
case resultDescription = "description"
case reminderTime = "reminder_time"
case sameDay = "same_day"
case beforeDay = "before_day"
case threeDays = "three_days"
case byEmail = "by_email"
case bySMS = "by_sms"
case byNotification = "by_notification"
case mp3Time = "mp3_time"
case fileName = "file_name"
case fileLink = "file_link"
case status
}
我希望它被正确解码,但我得到了一个奇怪的行为。 解码器显示 Int 变量的错误,表示预期的 Int 但找到了字符串/数据。当我将变量的类型更改为字符串时,它表示预期的字符串但找到了一个数字。当我尝试将其解析为 Bool 时,它也会引发类型不匹配。
【问题讨论】:
-
展示你对 JSONDecoder 的使用。另请注意,您的单个
Task结构与 JSON 不匹配,它只是其中的一部分。 -
我希望它能正确解码。不,不是。成员
success和result的结构在哪里?即使使用convertFromSnakeCase策略,解码器也不会将by_sms解码为bySMS。 -
更新了我的代码。
-
您应该显示您尝试解析的完整 json 响应,尤其是导致您出错的响应。仅显示其中的一部分会使诊断问题变得更加困难。正如@maddy 建议的那样,您还应该显示您正在使用的 JSONDecoder。
-
我无法用你上面的 JSON 和代码重现这个。它按照您的预期解码。这表明您在此处提供的 JSON 实际上并不是解码器中的内容,或者您在某处有一个自定义解码器(可能是
Object的一部分?)