How to make model class for following JSON response in swift iOS

前端 未结 6 1717
花落未央
花落未央 2021-02-10 14:40

Hi i am beginner for swift ios and my requirement is have to display Json response to table list i got response from web-services and response seems like below

MY requ

6条回答
  •  长发绾君心
    2021-02-10 14:52

    For mapping you can use Alamofire's extension ObjectMapper.

    Ex:

    [{
    "_id" : "5470def9e0c0be27780121d7",
    "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/5470def9e0c0be27780121d7_180.png",
    "name" : "Mondo",
    "hasVip" : false,
    "location" : {
        "city" : "Madrid"
    }
    }, {
        "_id" : "540b2ff281b30f3504a1c72f",
        "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/540b2ff281b30f3504a1c72f_180.png",
        "name" : "Teatro Kapital",
        "hasVippler" : false,
        "location" : {
            "address" : "Atocha, 125",
            "city" : "Madrid"
        }
    }, {
        "_id" : "540cd44581b30f3504a1c73b",
        "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/540cd44581b30f3504a1c73b_180.png",
        "name" : "Charada",
        "hasVippler" : false,
        "location" : {
            "address" : "La Bola, 13",
            "city" : "Madrid"
        }
    }]
    

    And mapper class:

    import ObjectMapper
    
    class Location: Mappable {
        var address: String?
        var city: String?
    
        required init?(map: Map){
    
        }
    
        func mapping(map: Map) {
            address <- map["address"]
            city <- map["city"]
        }
    }
    
    class Club: Mappable {
        var id: String?
        var imageUrl: Int?
        var name: String?
        var hasVip: Bool = false
        var location: Location?
    
        required init?(map: Map){
    
        }
    
        func mapping(map: Map) {
            id <- map["_id"]
            imageUrl <- map["imageUrl"]
            name <- map["name"]
            hasVip <- map["hasVippler"]
            location <- map["location"]
        }
    }
    

    And this way very flexible and transparent to use.

    https://github.com/Alamofire/Alamofire https://github.com/tristanhimmelman/AlamofireObjectMapper

    Using example:

    Alamofire.request(URL).responseArray { (response: DataResponse<[Club]>) in
    
        let clubs = response.result.value
    
        if let clubs = clubs {
            for club in clubs {
                print(club.name)
                print(club.location.city)           
            }
        }
    }
    

提交回复
热议问题