【发布时间】:2018-03-03 00:37:54
【问题描述】:
我正在尝试实现 Swift 4 的新 Decodable 协议,但遇到了一些困难。
这是我的 JSON 服务器响应:
{
"success": true,
"errorCode": 0,
"message": "Succcess",
"data": {
"name": "Logan Howlett",
"nickname": "The Wolverine",
"image": "http://heroapps.co.il/employee-tests/ios/logan.jpg",
"dateOfBirth": 1880,
"powers": [
"Adamantium Bones",
"Self-Healing",
"Adamantium Claws"
],
"actorName": "Hugh Jackman",
"movies": [
{
"name": "X-Men Origins: Wolverine",
"year": 2009
},
{
"name": "The Wolverine",
"year": 2013
},
{
"name": "X-Men: Days of Future Past",
"year": 2014
},
{
"name": "Logan",
"year": 2017
},
]
}
}
解码响应的data 部分的最佳方法是什么?
另外,如果data 突然变成array 而不是对象,我该如何支持这两种数据类型?
非常感谢:)
【问题讨论】:
-
Also, what happens if the data is suddenly an array instead of an object, how can I support both data types?— 使用enums 与您类型中的关联值?一种情况是array,另一种情况是dictionary。 -
您应该通读 Codable 文档中的 Encoding and Decoding Custom Types 以了解如何编写反映您的 JSON 表示的类型。这主要涉及编写类型并符合 Codable,其余的应该为您完成。
-
对于那些关注的人。另一个好书 (medium.com/swiftly-swift/…)
标签: swift swift4 codable decodable