1. 程式人生 > >[Swift通天遁地]四、網絡和線程-(11)將服務器返回的JSON映射為實例對象

[Swift通天遁地]四、網絡和線程-(11)將服務器返回的JSON映射為實例對象

add ide location set 寫代碼 pod 點擊 Language man

本文將演示使用第三方類庫中,將服務器返回的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 }

[Swift通天遁地]四、網絡和線程-(11)將服務器返回的JSON映射為實例對象