我想实现Swift 4的新的可解码协议,并有一些难以接近它。使用Swift 4的可解码协议嵌套JSON服务器响应
这是我的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
而不是对象会发生什么情况,我如何支持这两种数据类型?
感谢很多:)
'另外,如果数据突然变成一个数组而不是一个对象会发生什么,我该如何支持这两种数据类型? - 使用enum关联你的类型值?一个用'array',另一个用'dictionary'。 – user28434
您应该阅读Codable文档中的[Encoding and Decoding Custom Types](编码和解码自定义类型)(https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types),以了解如何编写镜像JSON表示的类型。大多数情况下,这涉及编写类型并符合Codable,其余部分应该为您完成。 –