简体   繁体   中英

Cannot convert value of type '()' to expected argument type 'Data'

Here is my problem :

A Json object is returned by the function fetch() and I would like to parse it with structures, Moreover the 'let welcome' does not accept my json object :

error message : Cannot convert value of type '()' to expected argument type 'Data'

There may be something wrong with the JSON Decoder function ?

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"
    }
}

The function fetch() does not return any value, so jsonData is just Void aka () .

You need to decode the response inside the AF.request handler:

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

Note that you can also use responseDecodable directly:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM