上一篇文章中咱們介紹了使用EVReflection解析JSON的方法,可是仍是用到了SwiftyJSON這樣的工具,那麼有木有什麼辦法可以更簡單的解決這樣的問題EVReflection的做者還爲咱們提供了AlamofireJsonToObjects這樣一個工具,讓咱們可以更加容易的處理JSON數據swift
AlamofireJsonToObjects 基於目前使用最普遍的Swift HTTP庫Alamofire和咱們上次提到的
EVReflectionsegmentfault
咱們經過CocoaPods導入api
use_frameworks! pod "AlamofireJsonToObjects"
在用到到Swift文件中import AlamofireJsonToObjects
數組
做爲EVReflection的一個配套工具,它的使用很是簡單,咱們經過一個Demo一塊兒來學習一下ruby
根據咱們上次寫出的數據模型,咱們寫出整個response的數據模型網絡
import Foundation import EVReflection class CityModel:EVObject{ var city_name = "" var city_pinyin = "" var short_name = "" var short_pinyin = "" var city_id = 100010000 }
以下工具
class CityModelApiResponse:EVObject{ var cities = [CityModel]() var errno = 0; var msg = ""; }
在咱們的文件中import AlamofireJsonToObjects
咱們此次先對Alamofire的網絡請求作一些封裝,咱們這裏使用了泛型以保證通用性
這裏再也不responseJSON
而是responseObject
學習
class func invokeObject< T: EVObject >( url:String, parameters:[String: AnyObject]? = nil, complete:(object: T?, error: NSError?) -> Void){ Alamofire.request(.GET, ServiceEndpointBase, parameters: nil, encoding: .URL, headers: ["apikey":"ownAPIKey"]).validate(statusCode: 200..<300).responseObject { (URLRequest:NSURLRequest?, HTTPURLResponse:NSHTTPURLResponse?, result:Result< T, NSError>) in complete(object: result.value, error: result.error) } }
接下來咱們寫具體的涉及業務的請求方法url
class func getCityListObject(complete:(object: CityModelApiResponse?, error: NSError?) -> Void){ invokeObject(ServiceEndpointBase,parameters: nil,complete: complete) }
咱們在viewDidLoad
方法中調用一下咱們的網絡請求方法code
ServiceProxy.getCityListObject { (object, error) in print(object!) }
控制檯結果以下
CityModelApiResponse { hash = 5326178534503437261 key = cities, value = ( { "city_id" = 100010000; "city_name" = "\U5317\U4eac\U5e02"; "city_pinyin" = beijing; "short_name" = "\U5317\U4eac"; "short_pinyin" = bj; }, { "city_id" = 500010000; "city_name" = "\U5929\U6d25\U5e02"; "city_pinyin" = tianjin; "short_name" = "\U5929\U6d25"; "short_pinyin" = tj; }, { "city_id" = 1800010000; "city_name" = "\U77f3\U5bb6\U5e84\U5e02"; "city_pinyin" = shijiazhuang; "short_name" = "\U77f3\U5bb6\U5e84"; "short_pinyin" = sjz; }, { "city_id" = 1800020000; "city_name" = "\U5510\U5c71\U5e02"; "city_pinyin" = tangshan; "short_name" = "\U5510\U5c71"; "short_pinyin" = ts; } ... ) key = errno, value = 0 key = msg, value = success }
AlamofireJsonToObjects不只提供了
responseObject
還有responseArray
,能夠直接導出數組