Ios ObjectMapper JSON与Swift中的alamofire
我想在Swift lang中处理JSON响应的工作,我在我的项目中使用了3个pod:-- 当http请求发送时,我希望在我的对象类中有JSON。没有问题。 这是我的密码 Contact.swift类:Ios ObjectMapper JSON与Swift中的alamofire,ios,swift,alamofire,Ios,Swift,Alamofire,我想在Swift lang中处理JSON响应的工作,我在我的项目中使用了3个pod:-- 当http请求发送时,我希望在我的对象类中有JSON。没有问题。 这是我的密码 Contact.swift类: import Foundation import ObjectMapper class Name: Mappable { var title: String! var first: String! var last: String! required init?
import Foundation
import ObjectMapper
class Name: Mappable {
var title: String!
var first: String!
var last: String!
required init?(_ map: Map) {
}
func mapping(map: Map) {
title <- map["title"]
first <- map["first"]
last <- map["last"]
}
}
class ContactsResponse: Mappable {
var gender: String!
var nameFull: [Name]?
required init?(_ map: Map) {
}
func mapping(map: Map) {
gender <- map["gender"]
nameFull <- map["name"]
}
}
let baseURL = "http://api.randomuser.me/"
override func viewDidLoad() {
super.viewDidLoad()
makeHTTPRequest()
}
func makeHTTPRequest() {
Alamofire.request(.GET, baseURL).responseObject { (response: Response<ContactsResponse, NSError>) in
let contactResponse = response.result.value
print(contactResponse?.gender) // print Nil :(
}
}
<代码>导入基础
导入对象映射器
类名:可映射{
变量标题:字符串!
首先:字符串!
最后:字符串!
必需的初始化(umap:map){
}
func映射(映射:映射){
title这可能是延迟响应,但请尝试检查您的“钥匙”是否有错误。 缩小问题的范围。因此,首先检查response.result.value是否为您提供了响应 如果我是对的,response.result.value==nil或键“gender”的映射都是错误的 我建议您使用if-let语句而不是let语句 比如说
if let contactResponse = response.result.value {
print(contactResponse?.gender)
} else {
//Handle error
}
这可能是延迟响应,但请尝试检查您的“钥匙”是否有错误。 缩小问题的范围。因此,首先检查response.result.value是否为您提供了响应 如果我是对的,response.result.value==nil或键“gender”的映射都是错误的 我建议您使用if-let语句而不是let语句 比如说
if let contactResponse = response.result.value {
print(contactResponse?.gender)
} else {
//Handle error
}
你找到答案了吗?你找到答案了吗