【问题标题】:Cannot convert value of type '()' to expected argument type 'Data'无法将类型“()”的值转换为预期的参数类型“数据”
【发布时间】:2020-06-14 00:16:58
【问题描述】:

这是我的问题:

函数 fetch() 返回一个 Json 对象,我想用结构解析它,而且“欢迎欢迎”不接受我的 json 对象:

错误消息:无法将类型“()”的值转换为预期的参数类型“数据”

JSON解码器功能可能有问题?

import Foundation
import Alamofire

func fetch() {
AF.request("https://shopping.yahooapis.jp/ShoppingWebService/V1/json/itemSearch?appid=XXXXXX&store_id=ejapan&jan=4901330197711").responseJSON { response in
        debugPrint(response.value!)
        return
    }
}

let jsonData = fetch()

let welcome = try? newJSONDecoder().decode(Welcome.self, from: jsonData)



struct Welcome: Codable {
    var resultSet: ResultSet

    enum CodingKeys: String, CodingKey {
        case resultSet = "ResultSet"
    }
}

【问题讨论】:

    标签: json swift api alamofire


    【解决方案1】:

    函数fetch() 不返回任何值,所以jsonData 只是Void 又名()

    您需要在 AF.request 处理程序中解码响应:

    AF.request("https://sh....").responseJSON { response in
            debugPrint(response.value!)
            let welcome = try? newJSONDecoder().decode(Welcome.self, from: response.data!)
        }
    }
    
    

    注意,你也可以直接使用responseDecodable

    AF.request("https://....").responseDecodable(of: Welcome.self) { response in
        debugPrint("Response: \(response)")
    }
    

    【讨论】:

    • 或者干脆用responseData代替responseJSON
    • responseDecodable 是处理Decodable 类型的推荐方式。
    猜你喜欢
    • 1970-01-01
    • 2016-03-21
    • 2016-07-27
    • 2016-07-02
    • 1970-01-01
    • 2020-03-01
    • 2016-08-01
    • 2017-02-07
    • 1970-01-01
    相关资源
    最近更新 更多