首页 > 解决方案 > Swift 4 + Alamofire:解析自定义结构数组

问题描述

我的 API 返回以下 JSON([CustomClass] 数组):

[{
        "name": "Name A",
        "startingDate": "2018-01-01",
        "duration": 4
    },
    {
        "name": "Name B",
        "startingDate": "2018-01-01",
        "duration": 4
    }
]

我正在使用 Alamofire 发出请求,然后解析 JSON:

static func test(parametersGet:Parameters, completion: @escaping ([CustomStruct]?, Error?) -> Void ) {
        Alamofire.request(API.test, parameters: parametersGet).validate().responseJSON { response in
            switch response.result {
            case .success:
                if let json = response.result.value {
                    let workoutCards = json as! [CustomStruct]
                    completion(workoutCards, nil)
                }
            case .failure(let error):
                completion(nil, error)
            }
        }
    }

CustomStruct 它只是一个带有这些键的 Codable 结构。

我收到以下错误:“无法将 '__NSDictionaryI' 类型的值转换为 'Project.CustomStruct'”。如何解析 JSON?

标签: swiftparsingalamofireswift4

解决方案


在您的情况下,您需要使用 JSONDecoder 将您的 jsonData 解码为 [CustomStruct]

  Alamofire.request(API.test, parameters: parametersGet).validate().responseJSON { response in
            switch response.result {
            case .success:
                if let jsonData = response.data {
                    let jsonDecoder = JSONDecoder()
                    do {
                        let workoutCards = try jsonDecoder.decode([CustomStruct].self, from: jsonData)
                        completion(workoutCards, nil)
                    }catch let error{
                        print(error.localizedDescription)
                        completion(nil, error)
                    }
                }
            case .failure(let error):
                completion(nil, error)
            }
        }

推荐阅读