Ios 使用Alamofire ObjectMapper映射到显示为nil的Swift对象问题
我不熟悉iOS和Swift开发环境。我试图使用Alamofire来提取JSON,并使用AlamoFileObject映射器将检索到的JSON集合映射回我的Swift对象 问题是我能够通过Alamofire请求获取JSON,并且显示了计数,但是映射部分似乎显示为零。是我错过的东西。谢谢你的帮助 模范班 提前谢谢 完整的JSON响应如下所示。在模型中只构建了所需的 [{“Id”:“16”,“areaId”:“17”,“name”:“Al-Aqiq”,“cityId”:“4”,“Zip”:“nameAr”:“\u0637\u0631\u064a\u0642\u0627\u0644\u0645”,“branchadr”:“test”,“branchadr 2”:“test”纬度:“24.60425”,“经度”:“46.629631”,“cityId”:“1”]Ios 使用Alamofire ObjectMapper映射到显示为nil的Swift对象问题,ios,json,swift2,alamofire,objectmapper,Ios,Json,Swift2,Alamofire,Objectmapper,我不熟悉iOS和Swift开发环境。我试图使用Alamofire来提取JSON,并使用AlamoFileObject映射器将检索到的JSON集合映射回我的Swift对象 问题是我能够通过Alamofire请求获取JSON,并且显示了计数,但是映射部分似乎显示为零。是我错过的东西。谢谢你的帮助 模范班 提前谢谢 完整的JSON响应如下所示。在模型中只构建了所需的 [{“Id”:“16”,“areaId”:“17”,“name”:“Al-Aqiq”,“cityId”:“4”,“Zip”:“nameA
我认为您缺少ObjectMapper库的正确文档。 看看这个 以下是库支持的类型:
Int
Bool
Double
Float
String
(枚举)RawRepresentable
数组
字典
对象
数组
数组
Set
字典
字典
- 以上所有选项
- 隐式展开上述选项
nil
在您的例子中是var-location:CLLocation?
如果需要映射CLLocation对象,一种方法是映射具有以下所有属性的CustomCLLocation:
JSON(我不知道你的JSON,这是一个例子)
Swift:创建另一个文件“CustomCLLocation”,例如第一个文件,但用于将CLLocation与Json映射
var latitude: Double?
var longitude: Double?
required init?(_ map: Map) {
mapping(map)
}
func mapping(map: Map) {
longitude <- map["long"]
latitude <- map["lat"]
}
使用转换:
var locationCLL = CLLocation.createFromCustomCLLocation(location) // now is a CLLocation
编辑:阿拉莫菲尔请求
我的应用程序上有与ios 8.0最新版本的AlamoFileObject Mapper相同的请求+
Alamofire.request(.GET, UrlEndpoints.branchUrl()).responseArray { (response: [BranchObjectMapper]?, error : ErrorType?) in
if(error != nil) {
print(error)
}else{
print("data downloaded")
if let response = response {
branchList(response)
for branch in self.branchList {
print(branch.id)
print(branch.name)
}
}
}
}
如果您在映射字符串和Int变量时遇到问题,那是因为您忘记在
var
之前添加dynamic
示例:
动态变量id:Int?
实际上我已经从映射中删除了CLLocation,以检查是否是由于相同的原因。但是我观察到所有其他字段也显示为零。非常感谢您的宝贵评论。我已经编辑了我的ask,只需检查新的Alamofire请求。很好,因为它正在工作。但是,这不是一个好的解决方案,因为您总是需要在任何地方处理转换。例如:您从CoreLocation管理器收到一个CLLocation,并希望保存它,然后您进行转换。同样的情况一直存在,并导致大量重复代码。您可以添加JSON吗?您的JSON响应具有属性“Id”在mapper类中,它是“id”(小写)。
var latitude: Double?
var longitude: Double?
required init?(_ map: Map) {
mapping(map)
}
func mapping(map: Map) {
longitude <- map["long"]
latitude <- map["lat"]
}
extension CLLocation {
public class func createFromCustomCLLocation(custom: CustomCLLocation) -> CLLocation {
return self.init(custom.latitude,custom.longitude)
}
}
var locationCLL = CLLocation.createFromCustomCLLocation(location) // now is a CLLocation
Alamofire.request(.GET, UrlEndpoints.branchUrl()).responseArray { (response: [BranchObjectMapper]?, error : ErrorType?) in
if(error != nil) {
print(error)
}else{
print("data downloaded")
if let response = response {
branchList(response)
for branch in self.branchList {
print(branch.id)
print(branch.name)
}
}
}
}