AlamofireObjectMapper在swift中

时间:2016-03-04 03:20:53

标签: json swift alamofire objectmapper

我想第一次使用AlamofireObjectMapper来解析swift中的json响应。

回复是:

{
    "city": {
        "total": 19,
        "data": [
            {
                "business_model": 2,
                "type": "Hotel"
            },
            {
                "business_model": 2,
                "type": "Hotel"
            }
        ]
    }
}

我这样映射:

class CityResponse: Mappable {

    var location: String?
    var data: [Data]?

    required init?(_ map: Map){

    }

    func mapping(map: Map) {
        data <- map["city.data"]

    }
}

class Data: Mappable {

    var business_model: String?
    required init?(_ map: Map){

    }

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

在我的控制器中:

Alamofire.request(.GET, "MY_URL").responseArray { (response: Response<[Data], NSError>) in

    print("res: \(response)")

    let forecastArray = response.result.value

    if let forecastArray = forecastArray {
        for forecast in forecastArray {
            print("model is : \(forecast.business_model)" )
        }
    }
}

它给了我错误映射。

1 个答案:

答案 0 :(得分:0)

您需要指出数组的路径: 的 responseArray(&#34;数据&#34)

Alamofire.request(.GET, "MY_URL").responseArray("data") { (response: Response<[Data], NSError>) in

    print("res: \(response)")

    let forecastArray = response.result.value

    if let forecastArray = forecastArray {
        for forecast in forecastArray {
            print("model is : \(forecast.business_model)" )
        }
    }
}