首页 > 解决方案 > 在 swift 中使用 JSONSerialization 和 JSONDecoder 有什么区别?

问题描述

在 swift 中使用 JSONSerialization 和 JSONDecoder 有什么区别,同时将 JSON 转换为 swift 模型?好像他们在做同样的工作。如果他们这样做,那么什么时候使用?先感谢您

标签: iosjsonswift

解决方案


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 模型类或结构。自行检查。


推荐阅读