Вы не анализируете верхний уровень JSON. (success
, errorCode
, message
и data
).
Код игровой площадки для тестирования ...
import Foundation
let jsonData = """
{
"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(using: .utf8)!
struct JSONResponse: Codable {
let success: Bool
let errorCode: Int
let message: String
let data: DataClass
}
struct DataClass: Codable {
let name: String?
let nickname: String?
let image: URL?
let dateOfBirth: Int?
let powers: [String]?
let actorName: String?
let movies: [Movie]?
enum CodingKeys: String, CodingKey {
case name = "name"
case nickname = "nickname"
case image = "image"
case dateOfBirth = "dateOfBirth"
case powers = "powers"
case actorName = "actorName"
case movies = "movies"
}
}
struct Movie: Codable {
let name: String?
let year: Int?
enum CodingKeys: String, CodingKey {
case name = "name"
case year = "year"
}
}
do {
let result = try JSONDecoder().decode(JSONResponse.self, from: jsonData)
print(result)
} catch {
print(error)
}