在 swift 中使用 JSONSerialization 和 JSONDecoder 有什么区别,同时将 JSON 转换为 swift 模型?好像他们在做同样的工作。如果他们这样做,那么什么时候使用?
先感谢您
最佳答案
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是符合可编码协议(protocol)的结构。
如果要解析手动 JSON 而不是使用可编码 ,iOS 有一个名为 JSONSerialization 的内置替代方案。但我认为每个人都想使用 JSONDecoder。还有 quicktype 创建 json 模型 的类或结构你免费 .
自行检查。
关于ios - 在 swift 中使用 JSONSerialization 和 JSONDecoder 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58363994/