Swift 4 + Alamofire:解析自定义结构数组

时间:2018-06-18 16:15:37

标签: swift parsing alamofire swift4

我的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?

2 个答案:

答案 0 :(得分:1)

在您的情况下,您需要使用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)
            }
        }

答案 1 :(得分:0)

您可以像这样构建一个结构:

    struct Item {
        var name: String
        var startingDate: String
        var duration: String
    }

然后从结果中解析数据:

                let jsonDecoder = JSONDecoder()
                do {
                    let workoutCards = try jsonDecoder.decode([Item].self, from: data)
                    completion(workoutCards, nil)
                }catch let error{
                    print(error.localizedDescription)
                    completion(nil, error)
                }
            }
        case .failure(let error):
            completion(nil, error)
        }