我想解码此JSON响应

时间:2019-07-10 05:07:48

标签: json swift

我正在尝试解码JSON对我的对象上传照片的响应,但是我遇到了错误。从(_) throws -> ()类型的抛出函数到(DefaultDataResponse) -> Void类型的非抛出函数的无效转换

DispatchQueue.main.async {

    let image = self.photo
    let uploaded_file = (image?.jpegData(compressionQuality: 0.2)!)!
    let url = URLs.profileImage

    Alamofire.upload(multipartFormData: { multipartFormData in
        multipartFormData.append(uploaded_file, withName: "uploaded_file",fileName: "uploaded_file", mimeType: "image/jpg") 
    }, to: url)
    { (result) in
        switch result {
        case .success(let upload, _, _):

            upload.uploadProgress(closure: { (progress) in
                print("Upload Progress: \(progress.fractionCompleted)")
            })

            upload.response { response in
                print(response.result.value!)
                let data = response.data

                print(JSON(response.data))
                let jsonDecoder = JSONDecoder()
                let res = try jsonDecoder.decode(uploadPhoto.self, from: data ) as uploadPhoto
            }

        case .failure(let encodingError):
            print(encodingError)
        }
    }
}

我想对响应进行解码。这样我就可以从JSON获取值。

JSON响应:

{
    "code": 200,
    "message": "Image Uploaded Successfully",
    "image_link": "uploads\/profile\/1562737080_icons8-key-50 (1).png"
}

2 个答案:

答案 0 :(得分:1)

如果 JSON 响应的格式为

{
    "code": 200,
    "message": "Image Uploaded Successfully",
    "image_link": "uploads/profile/1562737080_icons8-key-50 (1).png"
}
用于解析上述JSON的

模型就像

struct UploadPhoto: Codable {
    let code: Int
    let message: String
    let imageLink: String
}

解析,使用:

do {
    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    let response = try decoder.decode(UploadPhoto.self, from: data)
    print(response)
} catch {
    print(error)
}

答案 1 :(得分:0)

您是否尝试过使用respone.result.value?

if let resultDict = response.result.value as? [String: Any] {
    let message = resultDict ["message"]
    //...
}