[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

扫描二维码关注公众号,回复: 4803204 查看本文章

->【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 }

猜你喜欢

转载自www.cnblogs.com/strengthen/p/10229119.html