thunderbird7
thunderbird7

Reputation: 687

Swift: How to Convert JSON String with Alamofilre or SwiftyJSON to ObjectMapper?

I'm currently using ObjectMapper for Swift for mapping JSON Object from API to model Object

but my restful api return API look like this:

{
       success: true,
       data: 
       [{  
          "stats":{  
             "numberOfYes":0,
             "numberOfNo":2,
             "progress":{  
                "done":false,
                "absolute":"2/100",
                "percent":2
             }
          },
          "quickStats":null,
          "uid":5,
          "name":"Flora",
          "imageArray":[  
             "http://s3.com/impr_5329beac79400000",
             "http://s3.com/impr_5329beac79400001"
          ],
          "metaData":{  
             "description":"Floral Midi Dress",
             "price":"40$"
          }
       }]

}

In data node is array i can't look up to mapping with this code

let json = JSON(responseObject!)

for tests in json["impressions"][0] {
  let test = Mapper<myTests>().map(tests)
  println(test?.impressionID)
}

How should I fix? Thanks

** Edited ** I found solution similar @tristan_him

ObjectModel mapping structure

class Response: Mappable {
    var success: Bool?
    var data: [Data]?

    required init?(_ map: Map) {
        mapping(map)
    }

    func mapping(map: Map) {
        success <- map["success"]
        data <- map["data"]
    }
}

class Data: Mappable {
    var uid: Int?
    var name: String?
    // add other field which you want to map        

    required init?(_ map: Map) {
        mapping(map)
    }

    func mapping(map: Map) {
        uid <- map["uid"]
        name <- map["name"]
    }
}

Mapping with Alamofire response

let response: Response = Mapper<Response>().map(responseObject)!

for item in response.data! {
    let dataModel: Data = item
    println(dataModel.name)
}

Upvotes: 3

Views: 6820

Answers (1)

tristan_him
tristan_him

Reputation: 276

You can map the JSON above by using the following class structure:

class Response: Mappable {
    var success: Bool?
    var data: [Data]?

    required init?(_ map: Map) {
        mapping(map)
    }

    func mapping(map: Map) {
        success <- map["success"]
        data <- map["data"]
    }
}

class Data: Mappable {
    var uid: Int?
    var name: String?
    // add other field which you want to map        

    required init?(_ map: Map) {
        mapping(map)
    }

    func mapping(map: Map) {
        uid <- map["uid"]
        name <- map["name"]
    }
}

Then you can map it as follows:

let response = Mapper<Response>().map(responseObject)
if let id = response?.data?[0].uid {
    println(id)
}

Upvotes: 5

Related Questions