json - 使用 Codable swift 解析时忽略数组中的空对象

标签 json swift parsing codable swift4.2

我正在使用 swift Codable 解析这个 API

"total": 7,
"searchResult": [
    null,
    {
        "name": "joe"
        "family": "adam"
    },
    null,
    {
        "name": "martin"
        "family": "lavrix"
    },
    {
        "name": "sarah"
        "family": "mia"
    },
    null,
    {
        "name": "ali"
        "family": "abraham"
    }
]

使用这个 PaginationModel:

class PaginationModel<T: Codable>: Codable {
    var total: Int?
    var data: T?

    enum CodingKeys: String, CodingKey {
        case total
        case data = "searchResult"
    }

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.total = try container.decodeIfPresent(Int.self, forKey: .total)
        self.data = try container.decodeIfPresent(T.self, forKey: .data)
    }
}

用户模型:

struct User: Codable {
    var name: String?
    var family: String?
}

我这样调用 jsonDecoder 来解析 API json:

let responseObject = try JSONDecoder().decode(PaginationModel<[User?]>.self, from: json)

现在我的问题是 searchResult 数组中的 null。它解析正确,当我访问 paginationModel 中的 data 时,我在数组中找到了 null

如何在解析API时忽略所有null,结果将是一个没有任何null的数组

最佳答案

首先,我建议始终考虑 PaginationModel 由数组组成。您不必将 [User] 作为通用类型传递,您可以只传递 User。然后解析器可以使用它解析数组的知识并自动处理 null:

class PaginationModel<T: Codable>: Codable {
    var total: Int?
    var data: [T]?

    enum CodingKeys: String, CodingKey {
        case total
        case data = "searchResult"
    }

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.total = try container.decodeIfPresent(Int.self, forKey: .total)

        self.data = (try container.decodeIfPresent([T?].self, forKey: .data))?.compactMap { $0 }
    }
}

您可能想在此处删除可选值并改用一些默认值:

class PaginationModel<T: Codable>: Codable {
    var total: Int = 0
    var data: [T] = []

    enum CodingKeys: String, CodingKey {
        case total
        case data = "searchResult"
    }

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.total = (try container.decodeIfPresent(Int.self, forKey: .total)) ?? 0

        self.data = ((try container.decodeIfPresent([T?].self, forKey: .data)) ?? []).compactMap { $0 }
    }
}

关于json - 使用 Codable swift 解析时忽略数组中的空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55183539/

相关文章:

javascript - 访问 javascript 中的嵌套对象

Python 树存储来自 json 输入文件的表达式

swift - 如何使用 Swift 选择 UITextField 中的所有文本

ios - 获取 AppleWatch 的 GooglePlaces API(以及一般的异步调用)数据(使用 WCSession)

ios - 您可以使用 iOS 应用程序发送弹出通知吗?

parsing - 为我的语言编写解析器的最短方法是什么?

javascript - 使用 jQuery getJSON 解释/解析 JSON 数据

javascript - 如何通过for循环设置json数据

java - 如何在Java中解析JSON

MySQL 8 - 在 JSON_ARRAYAGG 中排序和过滤