AlamofireObjectMapper 6.2.0

AlamofireObjectMapper 6.2.0

测试已测试
语言语言 SwiftSwift
许可 MIT
发布上次发布2019年10月
SPM支持 SPM

Tristan Himmelman 维护。



 
依赖项
Alamofire= 5.0.0-rc.2
ObjectMapper~> 3.5.1
 

  • Tristan Himmelman

AlamofireObjectMapper

Build Status CocoaPods Carthage compatible

Alamofire 的一个扩展,它使用 ObjectMapper 自动将 JSON 响应数据转换为 Swift 对象。

用法

给定一个返回以下格式的天气数据的 URL

{
    "location": "Toronto, Canada",    
    "three_day_forecast": [
        { 
            "conditions": "Partly cloudy",
            "day" : "Monday",
            "temperature": 20 
        },
        { 
            "conditions": "Showers",
            "day" : "Tuesday",
            "temperature": 22 
        },
        { 
            "conditions": "Sunny",
            "day" : "Wednesday",
            "temperature": 28 
        }
    ]
}

您可以使用扩展如下使用

import AlamofireObjectMapper

let URL = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/d8bb95982be8a11a2308e779bb9a9707ebe42ede/sample_json"
Alamofire.request(URL).responseObject { (response: DataResponse<WeatherResponse>) in

    let weatherResponse = response.result.value
    print(weatherResponse?.location)
    
    if let threeDayForecast = weatherResponse?.threeDayForecast {
        for forecast in threeDayForecast {
            print(forecast.day)
            print(forecast.temperature)           
        }
    }
}

完战处理程序中的 WeatherResponse 对象是您定义的自定义对象。唯一的要求是对象必须遵守 ObjectMapper 的 Mappable 协议。在上面的例子中,WeatherResponse 对象看起来如下

import ObjectMapper

class WeatherResponse: Mappable {
    var location: String?
    var threeDayForecast: [Forecast]?
    
	required init?(map: Map){

	}
    
    func mapping(map: Map) {
        location <- map["location"]
        threeDayForecast <- map["three_day_forecast"]
    }
}

class Forecast: Mappable {
    var day: String?
    var temperature: Int?
    var conditions: String?
    
	required init?(map: Map){

	}
    
    func mapping(map: Map) {
        day <- map["day"]
        temperature <- map["temperature"]
        conditions <- map["conditions"]
    }
}

此扩展使用泛型允许您创建自己的自定义响应对象。下面是 responseObject 函数定义。只需将 T 替换为您的自定义响应对象,并扩展处理其余部分

public func responseObject<T: BaseMappable>(queue: DispatchQueue? = nil, keyPath: String? = nil, mapToObject object: T? = nil, context: MapContext? = nil, completionHandler: @escaping (DataResponse<T>) -> Void) -> Self

responseObject 函数有 4 个可选参数和一个必需的完战处理程序

  • queue:完战处理程序分发的队列。
  • keyPath:对象映射应该执行的 JSON 的键路径。
  • mapToObject:在它上面执行映射的对象。
  • context:传递给映射函数的 上下文 对象。
  • completionHandler:在请求完成并由 ObjectMapper 映射数据后执行的闭包。

嵌套对象的简单映射

AlamofireObjectMapper 支持在键中使用点符号来简化嵌套对象的映射。以下是一个 JSON 字符串示例

"distance" : {
     "text" : "102 ft",
     "value" : 31
}

您可以按如下方式访问嵌套对象

func mapping(map: Map) {
    distance <- map["distance.value"]
}

查看完整文档

键路径

keyPath 变量用于深入 JSON 响应,并只映射在此 keyPath 找到的数据。它支持像 data.weather 这样的嵌套值,以在 JSON 响应中深入多个级别。

let URL = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/2ee8f34d21e8febfdefb2b3a403f18a43818d70a/sample_keypath_json"
let expectation = expectationWithDescription("\(URL)")

Alamofire.request(URL).responseObject(keyPath: "data") { (response: DataResponse<WeatherResponse>) in
    expectation.fulfill()
    
    let weatherResponse = response.result.value
    print(weatherResponse?.location)
    
    if let threeDayForecast = weatherResponse?.threeDayForecast {
        for forecast in threeDayForecast {
            print(forecast.day)
            print(forecast.temperature)           
        }
    }
}

数组响应

如果您有一个返回数据为 Array 格式的端点,您可以使用以下函数将其映射

public func responseArray<T: Mappable>(queue queue: dispatch_queue_t? = nil, keyPath: String? = nil, completionHandler: DataResponse<[T]> -> Void) -> Self

例如,如果您的端点返回以下数据

[
    { 
        "conditions": "Partly cloudy",
        "day" : "Monday",
        "temperature": 20 
    },
    { 
        "conditions": "Showers",
        "day" : "Tuesday",
        "temperature": 22 
    },
    { 
        "conditions": "Sunny",
        "day" : "Wednesday",
        "temperature": 28 
    }
]

您可以这样请求和映射它

let URL = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/f583be1121dbc5e9b0381b3017718a70c31054f7/sample_array_json"
Alamofire.request(URL).responseArray { (response: DataResponse<[Forecast]>) in

    let forecastArray = response.result.value
    
    if let forecastArray = forecastArray {
        for forecast in forecastArray {
            print(forecast.day)
            print(forecast.temperature)           
        }
    }
}

安装

您可以使用 CocoaPods 将 AlamofireObjectMapper 添加到项目中,方法是在您的 Podfile 中添加以下行

pod 'AlamofireObjectMapper', '~> 5.2'

如果您使用的是 Carthage,您可以通过将其添加到您的 Cartfile 来添加对 AlamofireObjectMapper 的依赖

github "tristanhimmelman/AlamofireObjectMapper" ~> 5.2