无论我使用哪种类型,都会出现“类型不匹配”

时间:2019-09-10 18:36:59

标签: swift codable decodable

我正在尝试使用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但找到了字符串/数据。当我将变量的类型更改为String时,它说应该是String,但找到了一个数字。当我尝试将其解析为Bool时,它还会引发Type Mismatch。

1 个答案:

答案 0 :(得分:-1)

您的结构应该是这样的:

class Task: Codable { var success: Bool var result: [Result] var error: String? }

class Result: Codable
{

var sameDay: Int
var beforeDay: Int
var threeDays: Int
var by_email: Int
var by_sms: Int
var by_notification: Int

}

尝试