swift4.0 Alamofire +SwiftyJSON+ObjectMapper解析模型

刚开始看的时候有点乱,但是不要慌,这里有你想要的答案,请给自己点耐心。

先看json数据

{
address = "8\U53f7";
conseventid = 59;
headphoto = "http://onh8hmni9.bkt.clouddn.com/1.jpg";
ordertime = "1970-1-1 9:00:01";
ordertimestatu = 0;
releasetime = "2017-4-7 13:32:57";
roomphoto =     (
{
img1 = "http://onh8hmni9.bkt.clouddn.com/img1.png";
},
{
img2 = "http://onh8hmni9.bkt.clouddn.com/img2.png";
},
{
img3 = "http://onh8hmni9.bkt.clouddn.com/img3.png";
}
);
username = "\U6211\U662f\U5361\U7c73\U4e9a1";
userneed = "\U5f00\U59cb\U4e86";
}

这个json中包含有嵌套的同模型

模型文件

import UIKit
import SwiftyJSON
import ObjectMapper

class XLJModel: NSObject,Mappable{

    var address : String!
    var conseventid : String!
    var headphoto : String!
    var ordertime : String!
    var ordertimestatu : String!
    var releasetime : String!
    var roomphoto : [DetailRoomphotoModel]!
    var username : String!
    var userneed : String!
    
    required init?(map: Map) {
        
    }
    
    func mapping(map: Map) {
        
        address <- map["address"]
        conseventid <- map["conseventid"]
        headphoto <- map["headphoto"]
        ordertime <- map["ordertime"]
        releasetime <- map["ordertime"]
        username <- map["username"]
        userneed <- map["userneed"]
        roomphoto <- map["roomphoto"]
    }
    

}

class DetailRoomphotoModel : Mappable{
    
    var img1 : String!
    var img2 : String!
    var img3 : String!

    required init?(map: Map) {
        
    }
    
    func mapping(map: Map) {
        img1 <- map["img1"]
        img2 <- map["img2"]
        img3 <- map["img3"]
    }

    
}

如何使用的呢?

    override func touchesBegan(_ touches: Set, with event: UIEvent?) {
        do {
            tool.loadData(callBack: { (respone) in
                print("获取到的数据:\(respone)")
            })
            
            XLJNetworkTools.request.forGet(url: "http://onh8hmni9.bkt.clouddn.com/testGrap.json").success({ (respone) in

              //最外层的大模型
                let model = Mapper().map(JSON: respone as! [String : Any])
                for item in (model?.roomphoto)!{
              //嵌套的模型
                    let smod = Mapper().map(JSONObject: item)
                }
            }).failure({ (error) in
                print("error:\(String(describing: error))")
            })
            
        }
    }

封装的Alamofire在demo中请下载详看,有借鉴别人的。

Demo下载地址

你可能感兴趣的:(swift4.0 Alamofire +SwiftyJSON+ObjectMapper解析模型)