术语 3.2.1

术语 3.2.1

测试已测试
语言语言 SwiftSwift
许可证 MIT
发布最后发布2020年9月
SPM支持SPM

Harlan Kellaway维护。



术语 3.2.1

  • 作者
  • Harlan Kellaway

Gloss

🚨弃用通知🚨

Gloss已经弃用,以支持Swift的Codable框架。

现有的Gloss源代码不会消失,但更新将仅支持迁移到Codable。现在阅读迁移指南以开始。

如果您项目中还没有任何Gloss模型,但目前正在考虑JSON解析使用Gloss,现在立即改用Swift的Codable框架。

我明白,我还是想使用Gloss

Swift version CocoaPods Carthage compatible SPM CocoaPods Build Status

查看之前README.md中的使用Gloss的说明。

鸣谢

Gloss由Harlan Kellaway创建。

感谢所有贡献者和Swift社区对Gloss过去5年的支持!💖

许可证 License

更多信息请参阅LICENSE文件。

编解码迁移快速参考

以下是在准备好迁移到编解码之前,您的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数组

对于《Decodable》和《Encodable》模型的数组同样适用,分别对应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