Gloss

🚨 弃用通知 🚨

Gloss 已被弃用,建议使用 Swift 的 Codable 框架。

现有的 Gloss 源代码不会消失,但只会进行更新以支持迁移到 Codable。 立即阅读迁移指南以开始使用。

如果你的项目中还没有任何 Gloss 模型,并且正在考虑使用它进行 JSON 解析,请立刻放弃! 选择 Swift 的 Codable 框架代替。

我了解,但我仍然要使用 Gloss

Swift version CocoaPods Carthage compatible SPM CocoaPods Build Status

请参阅 之前的 README.md,了解在 Codable 迁移之前使用 Gloss 的说明。

鸣谢

Gloss 由 Harlan Kellaway 创建

感谢所有贡献者和 Swift 社区对 Gloss 五年来的支持! 💖

许可证 License

有关更多信息,请参阅 LICENSE 文件。

Codable 迁移快速参考

以下是在准备迁移到 Codable 后,您的 Gloss 模型和调用位置应具有的参考。

有关更多详细信息,请参阅 迁移指南

版本

使用 3.2.0 或更高版本以利用迁移助手。

反序列化

给定一个符合 JSONDecodable 的 Gloss 模型,添加对 Decodable 的符合性。 看起来像这样的模型

import Gloss

struct MyModel: JSONDecodable {
    let id: Int?
    
    init?(json: JSON) {
        self.id = "id" <~~ json
    }
}

添加

extension MyModel: Decodable {

    init(from decoder: Swift.Decoder) throws {
        // Proper Decodable definition or throw GlossError.decodableMigrationUnimplemented
        // Remove this method if Codable can synthesize decoding for you
    }

}

从 JSON 初始化模型

当前初始化该模型的方式如下所示

let myModel = MyModel(json: someJSON)

变为

let myModel: MyModel = .from(decodableJSON: someJSON)

序列化

给定一个符合 JSONEncodable 的 Gloss 模型,添加对 Encodable 的符合性。 看起来像这样的模型

import Gloss

struct MyModel: JSONEncodable {
    let id: Int?
    
    func toJSON() -> JSON? {
        return jsonify(["id" ~~> self.id])
    }
}

添加

extension MyModel: Encodable {

    func encode(to encoder: Swift.Encoder) throws {
        // Proper Encodable defintion or throw GlossError.encodableMigrationUnimplemented
        // Remove this method if Codable can synthesize encoding for you
    }

}

将模型对象转换为 JSON

当前转换为 JSON 的方式如下所示

let json: JSON? = myModel.toJSON()

变为

let json: JSON? = myModel.toEncodableJSON()

JSON 数组

类似的使用方法适用于 DecodableEncodable 模型的数组,分别使用 from(decodableJSONArray:)toEncodableJSONArray()

配置 JSONDecoderJSONEncoder

如果您的 Codable 定义健全但遇到 Codable 错误,请确保您的 JSONDecoderJSONEncoder 实例配置正确,并在调用位置传递它们

let mySharedJSONDecoder: JSONDecoder = ...
let myModel: MyModel = .from(decodableJSON: someJSON, jsonDecoder: mySharedJSONDecoder)
let mySharedJSONEncoder: JSONEncoder = ...
let json: JSON? = myModel.toEncodableJSON(jsonEncoder: mySharedJSONEncoder)

使用 Data 而不是 JSON 来创建模型

在您开始依赖 Gloss 的 JSON 类型的地方,您最终需要传递 Data,因为这是 Codable 使用的。 为了快速开始使用 decode(:),一种选择是使用 Gloss 使用的相同方法来进行 Data 转换

import Gloss

let sharedGlossSerializer: GlossJSONSerializer = ...
let json: JSON = ...
if let data: Data? = sharedGlossSerializer.data(from: json, options: nil) {
    let myModel: MyModel = try? myJSONDecoder.decode(MyModel.self, from : data)
    ...
}

抓住这次迁移的机会,将您的模型精简到 Codable 所需的少量代码,并将您的网络代码从 JSON 序列化的细节中分离出来。 未来的你将会感激不尽! 🔮

✨✨✨EOF✨✨✨