AlamofireJsonToObjects+EVReflection:一步解決JSON解析

上一篇文章中咱們介紹了使用EVReflection解析JSON的方法,可是仍是用到了SwiftyJSON這樣的工具,那麼有木有什麼辦法可以更簡單的解決這樣的問題EVReflection的做者還爲咱們提供了AlamofireJsonToObjects這樣一個工具,讓咱們可以更加容易的處理JSON數據swift

AlamofireJsonToObjects 基於目前使用最普遍的Swift HTTP庫Alamofire和咱們上次提到的
EVReflectionsegmentfault

第三方庫導入

咱們經過CocoaPods導入api

use_frameworks!
pod "AlamofireJsonToObjects"

在用到到Swift文件中import AlamofireJsonToObjects數組

Demo

做爲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,能夠直接導出數組

相關文章
相關標籤/搜索