我应该如何使用URLSession获取JSON对象,以便我可以将它从ObjectMapper转换为Map对象?这是我从API服务器获取数据的代码:
func makeGetRequest(completionHandler: @escaping ((AnyObject?) -> Void)) {
let session = URLSession(configuration: .default)
guard let requestUrl = URL(string:buildUrl()) else { return }
var request = URLRequest(url:requestUrl)
//HEADERS
request.addValue("multipart/form-data; charset=utf-8", forHTTPHeaderField: "Content-Type");
let token = CredentialsManager.sharedInstance().token;
if (!(token?.isEmpty)!) {
request.addValue(token!, forHTTPHeaderField: "X-Auth-Token");
};
let task : URLSessionDataTask = session.dataTask(with: request, completionHandler: {(data, response, error) in
guard let data = data, error == nil else { return }
do {
let resultJSON = try JSONSerialization.jsonObject(with: data) as! [[String:AnyObject]]
completionHandler(resultJSON as AnyObject?)
} catch let error as NSError {
// Handle error
}
});
task.resume()
}
这是我要求获取数据的函数:
public func getUser() {
makeGetRequest() { (result) -> Void in
let resultModel = UserModel(map: result as! Map)
self.resultDelegate.onUserRequestSuccess(model: resultModel!)
}
}
这是我的UserModel实现可映射协议:
class UserModel : Mappable {
var id: Int?
var username: String?
required init?(map: Map) {
}
// Mappable
func mapping(map: Map) {
id <- map["id"]
username <- map["username"]
}
}
在打电话的时候
UserModel(map: result as! Map)
我收到错误:
无法将“__NSDictionaryI”类型的值转换为“NSArray”
答案 0 :(得分:0)
下面使用JSONSerialization获取响应是ObjectMapper的代码:
let headers: HTTPHeaders = ["Accept": "application/json", "Authorization": authBearer]
Alamofire.request(url, method: .get, parameters: nil, headers: headers).responseJSON { response in
print(response.result.value ?? "")
let json = try! JSONSerialization.jsonObject(with: response.data!, options: [])
let report = Mapper<Department>().map(JSON: json as! [String : Any])
print(report?.department[0].employee[0].first_name ?? "")
}
class Department: Mappable {
var department = [Directory]()
required convenience init?(map: Map) {
self.init()
}
func mapping(map: Map) {
department <- map["department"]
}
}
class Directory:Mappable {
var id = 0
var name = ""
var employee = [Employee]()
var genre = ""
//Impl. of Mappable protocol
required convenience init?(map: Map) {
self.init()
}
func mapping(map: Map) {
id <- map["id"]
name <- map["name"]
employee <- map["employee"]
genre <- map["genre"]
}
}
class Employee: Mappable {
var address = ""
var dob = ""
var email = ""
var first_name = ""
var last_name = ""
var phone_number = ""
required convenience init?(map: Map) {
self.init()
}
func mapping(map: Map) {
address <- map["address"]
dob <- map["dob"]
email <- map["email"]
first_name <- map["first_name"]
last_name <- map["last_name"]
phone_number <- map["phone_number"]
}
}