ios - 在 swift 中使用 JSONSerialization 和 JSONDecoder 有什么区别?

标签 ios json swift

在 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/

相关文章:

ios - 无法将类型 '__NSCFString' 的值转换为 'NSDictionary'

javascript - 为什么 JSON 只允许字符串作为键?

java - Mule中如何动态插入json数据到数据库中

swift - 无法使用 swift 在 safari 浏览器本地存储中存储值

swift - 如何使 View 响应触摸(而不是点击)

iOS - 为 Storyboard检测 iPad/iPhone 设备的逻辑

iphone - 在 iOS 设备上截屏时如何修复丢失的 "blocks"数据?

ios - Estimote Ibeacon 无法在 Mac 上检测到 2011 年底

python - 使用 Pandas 库将 JSON 转换为 CSV

ios - UILabel向下滑动发送错误信息