
问题是我能够通过Alamofire请求获取JsON并显示计数,但映射部分似乎显示为零.是我错过了什么.感谢帮助.
模型类
import UIKitimport CoreLocationimport ObjectMapperclass BranchObjectMapper : Mappable { // MARK: PropertIEs var ID: Int? var cityID: Int? var areaID: Int? var name: String? var nameAr: String? var branchAddr: String? var branchAddr2: String? var location: CLLocation? required init?(_ map: Map) { mapPing(map) } func mapPing(map: Map) { ID <- map["ID"] cityID <- map["cityID"] areaID <- map["areaID"] name <- map["name"] nameAr <- map["nameAr"] branchAddr <- map["branchAddr"] branchAddr2 <- map["branchAddr2"] location <- map["location"] }} 在vIEwDIDLoad()中请求部分
Alamofire.request(.GET,UrlEndpoints.branchUrl()).responseArray { (response: Response<[BranchObjectMapper],NSError>) in self.branchList = response.result.value! print(self.branchList.count) // count is correct for branch in self.branchList { print(branch.ID) // prints nil print(branch.ID) // prints nil }} 提前致谢
完整的JsON响应如下所示.在Model中只构建了需要的东西.
解决方法 我想你错过了ObjectMapper lib的正确文档.[{“ID”:”16″,”areaID”:”17″,”name”:”Al Aqiq”,”cityID”:4”,”Zip”:””,”nameAr”:”\u0637\u0631\u064a\u0642 \u0627\u0644\u0645″,”branchAddr”:”test”,”branchAddr2″:”test”Latitude”:”24.60425″,”Longitude”:”46.629631″,”cityID”:”1″}]
检查这个 Github ObjectMapper.
这些是lib支持的类型:
>国际
>布尔
>双倍
>漂浮
>字符串
> RawRepresentable(枚举)
>数组< AnyObject>
> Dictionary< String,AnyObject>
>对象< T:可映射>
>数组< T:Mappable>
> Array< Array< T:Mappable>>
> Set< T:Mappable>
> Dictionary< String,T:Mappable>
> Dictionary< String,Array< T:Mappable>>
>以上所有选项
>以上隐含的解包方案
因此,如果您尝试映射不在该列表中的Object,则结果为nil.
在你的情况下是var location:CLLocation?.
如果需要映射CLLocation对象,一种方法是将CustomCLLocation映射到所有属性,如下所示:
JsON(我不知道你的Json,这是一个例子)
"location":{ "long": 43.666,"lat": 73.4} 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"]} 现在,您可以映射“假”CLLocation对象:
var location:CustomCLLocation?
然后,如果你想要一个真正的CLLocation.只需像这样创建一个Simply Extension(将它添加到CustomCLLocation文件中):
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请求
我在我的应用程序上使用最新版本的AlamofireObjectMapper for ios 8.0获得了相同的请求
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) } } }} 总结 以上是内存溢出为你收集整理的ios – 映射到Swift对象问题,显示使用Alamofire ObjectMapper的nil全部内容,希望文章能够帮你解决ios – 映射到Swift对象问题,显示使用Alamofire ObjectMapper的nil所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)