1. 程式人生 > >[Swift通天遁地]四、網路和執行緒-(11)將伺服器返回的JSON對映為例項物件

[Swift通天遁地]四、網路和執行緒-(11)將伺服器返回的JSON對映為例項物件

本文將演示使用第三方類庫中,將伺服器返回的JSON對映為例項物件。

首先確保在專案中已經安裝了所需的第三方庫。

點選【Podfile】,檢視安裝配置檔案。

1 platform :ios, ’12.02 use_frameworks!
3 
4 target 'DemoApp' do
5     source 'https://github.com/CocoaPods/Specs.git'
6     pod 'Alamofire', '~> 4.0'
7     pod 'AlamofireObjectMapper', '~> 4.0'
8 end

根據配置檔案中的相關配置,安裝第三方庫。

然後點選開啟【DemoApp.xcworkspace】專案檔案。

接著建立一個類檔案,作為返回資料被對映的例項物件。

在專案資料夾【DemoApp】上點選滑鼠右鍵,彈出右鍵選單。

【New File】->【Cocoa Touch Class】->【Next】->

【Class】:Forecast

【Subclass of】:Mappable

【Language】:Swift

->【Next】->【Create】

 1 //將新建檔案引入的預設類庫進行修改。
 2 //修改成上文安裝的對映庫。
 3 import ObjectMapper
 4
5 class Forecast: Mappable 6 { 7 //新增三個屬性 8 var day: String? 9 var temperature: Int? 10 var conditions: String? 11 12 //新增一個必須實現的初始化方法 13 required init?(map: Map) 14 { 15 16 } 17 18 //新增一個對映方法 19 func mapping(map: Map) 20 {
21 //依次將Map中的內容,對映到物件的三個屬性 22 day <- map["day"] 23 temperature <- map["temperature"] 24 conditions <- map["conditions"] 25 } 26 }

繼續建立一個類檔案,作為返回資料被對映的例項物件。

在專案資料夾【DemoApp】上點選滑鼠右鍵,彈出右鍵選單。

【New File】->【Cocoa Touch Class】->【Next】->

【Class】:WeatherResponse

【Subclass of】:Mappable

【Language】:Swift

->【Next】->【Create】

 1 //將新建檔案引入的預設類庫進行修改。
 2 //修改成上文安裝的對映庫。
 3 import ObjectMapper
 4 
 5 class WeatherResponse: Mappable
 6 {
 7     //新增一個字串的屬性,表示天氣情況的地理位置
 8     var location: String?
 9     //建立一個物件陣列,表示三天內的天氣情況。
10     //物件所屬的類,就是上文建立的包含三個屬性的天氣預報類。
11     var threeDayForecast: [Forecast]?
12     
13     //新增一個必須實現的初始化方法
14     required init?(map: Map)
15     {
16         
17     }
18     
19     //新增一個對映方法
20     func mapping(map: Map)
21     {
22         //依次將Map中的內容,對映到物件的兩個屬性
23         location <- map["location"]
24         threeDayForecast <- map["three_day_forecast"]
25     }
26 }

在專案導航區,開啟檢視控制器的程式碼檔案【ViewController.swift】

現在開始編寫程式碼,訪問一個天氣預報的資料介面,

並將伺服器返回的資料,對映成自定義的物件。

 1 import UIKit
 2 //在當前的類檔案中,引入已經安裝的第三方類庫
 3 import Alamofire
 4 import AlamofireObjectMapper
 5 
 6 class ViewController: UIViewController {
 7 
 8     override func viewDidLoad() {
 9         super.viewDidLoad()
10         // Do any additional setup after loading the view, typically from a nib.
11         //處理伺服器返回物件
12         responseObjectExample()
13 
14         //處理伺服器返回陣列
15         responseArrayExample()
16     }
17     
18     //新增一個方法,用來處理伺服器返回物件的情況。
19     func responseObjectExample()
20     {
21         //初始化一個字串常量,作為伺服器的介面。
22         let URL = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/d8bb95982be8a11a2308e779bb9a9707ebe42ede/sample_json"
23         
24         //呼叫網路操作庫的網路請求方法,訪問該介面,
25         //並將返回的資料,轉換成自定義的物件。
26         Alamofire.request(URL).responseObject {
27             (response: DataResponse<WeatherResponse>) in
28             
29             //獲得轉換後的物件,
30             let weatherResponse = response.result.value
31             //並在控制檯輸出物件的地理位置
32             print(weatherResponse?.location)
33             
34             //獲得物件的包含未來三日天氣情況的陣列屬性
35             if let threeDayForecast = weatherResponse?.threeDayForecast
36             {
37                 //遍歷陣列
38                 for forecast in threeDayForecast
39                 {
40                     //在控制檯輸出日期資訊
41                     print("forecast.day:\(forecast.day)")
42                     //在控制檯輸出溫度資訊
43                     print("forecast.temperature:\(forecast.temperature)")
44                 }
45             }
46         }
47     }
48     
49     //新增一個方法,處理返回陣列
50     func responseArrayExample()
51     {
52         //初始化一個字串常量,作為伺服器的介面。
53         let URL = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/f583be1121dbc5e9b0381b3017718a70c31054f7/sample_array_json"
54         
55         //呼叫網路操作庫的網路請求方法,訪問該介面,
56         //並將返回的資料,轉換成自定義的物件。
57         Alamofire.request(URL).responseArray {
58             (response: DataResponse<[Forecast]>) in
59             
60             //獲得伺服器返回的資料
61             let forecastArray = response.result.value
62             
63             //處理伺服器返回的陣列
64             if let forecastArray = forecastArray
65             {
66                 //遍歷陣列
67                 for forecast in forecastArray
68                 {
69                     //在控制檯輸出日期資訊
70                     print("forecast.day:\(forecast.day)")
71                     //在控制檯輸出溫度資訊
72                     print("forecast.temperature:\(forecast.temperature)")
73                 }
74             }
75         }
76     }
77 
78     override func didReceiveMemoryWarning() {
79         super.didReceiveMemoryWarning()
80         // Dispose of any resources that can be recreated.
81     }
82 }