ios - 在 swift 中使用 JSONSerialization 和 JSONDecoder 有什么区别?
问题描述
在 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是符合可编码协议的结构。
如果你想手动解析 JSON而不是使用Codable,iOS 有一个内置的替代方法,称为 JSONSerialization。但我认为每个人都想使用 JSONDecoder。而且quicktype还免费为你创建 json 模型类或结构。自行检查。
推荐阅读
- html - div 上线性渐变背景的不同悬停行为
- jenkins - 忽略 Jenkins 中的旧版本
- html - 角度材质:如何避免关注背景背景中的元素?
- maven - spring boot 的构建错误 - 无法传输 org.springframework.boot:spring-boot-starter-parent:pom:2.0.1.RELEASE
- php - 在 Laravel Passport 中限制客户端授权
- ruby-on-rails - 如何在我的规范中批准 PayPal 付款?
- vba - 如何根据 word 中带有宏的前导字符更改标题样式?
- android - ALTBEACON 库 - 后台模式?
- c++ - 如何设置参数以使用 QProcess 运行类文件?
- c - C - 读取文件时的无限循环