[英]What's the difference between using JSONSerialization and JSONDecoder in swift?
What's the difference between using JSONSerialization and JSONDecoder in swift, while converting JSON to a swift model? 好像他们在做同样的工作。 如果他们这样做,那么什么时候使用? 先感谢您
使用 JSONDecoder !
如果我没记错的话,JSONDecoder 出现在 Xcode 9 中,带有 Swift4。 编码和解码 JSON 更加简洁高效。 为此,您的 Swift Class 必须符合可解码协议。
JSON 序列化是老派。 (像 Objective-C 一样)
Apple 提供了 JSONDecoder,这在 swift4 及更高版本中是一个巨大的解脱。 我们可以在一行中解码 json。 例如
{// sample from quicktype app online
"greeting": "Welcome to quicktype!",
"instructions": [
"Type or paste JSON here",
"Or choose a sample above",
"quicktype will generate code in your",
"chosen language to parse the sample data"
]
}
// MARK: - Welcome
struct Welcome: Codable {
let greeting: String
let instructions: [String]
}
// let welcome = try? newJSONDecoder().decode(Welcome.self, from: jsonData)
这里welcome是符合可编码协议的结构。
如果你想手动解析JSON而不是使用Codable ,iOS 有一个内置的替代方案,称为 JSONSerialization。但我认为每个人都想使用 JSONDecoder。 而且 quicktype 还免费为您创建 json model类或结构。 自行检查。
近年来,JSON 已成为互联网上使用最广泛的数据传输格式。 在 iOS 开发的世界中,开发人员使用 Swift 中的 JSON 数据并将其用于构建 Z411ZCBD 应用程序是很常见的。 有一些很酷的库,如 SwiftyJSON,已经可用于处理 Swift 中的 JSON 数据,这些库变得很流行,因为开发人员不需要使用 JSONSerialization 处理不可读的混乱来解析 Z0ECD11C1D7A287401DZD148A2F。 幸运的是,Swift 4 引入了令人惊叹的 Codable 协议作为 Foundation 框架的一部分,并且 JSON 解析变成了一行或几行代码。 这是 Apple 完全支持的解决方案,可以轻松采用。 它提供了定制来编码和解码复杂场景的痛苦。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.