
現(xiàn)實(shí)中的網(wǎng)絡(luò)API
json 已經(jīng)成為現(xiàn)代網(wǎng)絡(luò) api 的標(biāo)準(zhǔn)數(shù)據(jù)格式,比如國家氣象局的查詢接口:
http://www.weather.com.cn/data/sk/101010100.html
{
"weatherinfo": {
"city": "北京",
"cityid": "101010100",
"temp": "18",
"WD": "東南風(fēng)",
"WS": "1級",
"SD": "17%",
"WSE": "1",
"time": "17:05",
"isRadar": "1",
"Radar": "JC_RADAR_AZ9010_JB",
"njd": "暫無實(shí)況",
"qy": "1011",
"rain": "0"
}
}
json 的格式一般為:
- 對象(object):一個(gè)對象以
{開始,并以}結(jié)束 - 稱/值(collection):名稱和值之間使用
:隔開,一般的形式是:
{name:value}
現(xiàn)實(shí)中的iOS網(wǎng)絡(luò)請求
因?yàn)?iOS 提供的原生框架—— NSURLSession ——提供的方法要求很多底層參數(shù),使用不直觀,錯誤處理也不穩(wěn)定,實(shí)際開發(fā)中我們都會選擇網(wǎng)絡(luò)框架,AFNetworking 是目前這方面的首選。它不單封裝了 NSURLSession 的請求,還會自動分配請求隊(duì)列,并格式化返回值,把 json 字符串轉(zhuǎn)成 字典。總之就是省時(shí)省力。
還有空氣般無處不在的對象
iOS開發(fā)中,任何數(shù)據(jù)都是基于OC對象,那么,問題來了:請求到的 json 數(shù)據(jù)怎么轉(zhuǎn)成可使用的對象呢?
一種實(shí)踐是,自己定義一套APP端要用的對象,再逐個(gè)實(shí)現(xiàn)從字典轉(zhuǎn)換的方法,每個(gè)請求都要自己實(shí)現(xiàn)一套,這個(gè)編碼過程麻煩(且重復(fù))不說,接口數(shù)量一多,還容易混亂。
現(xiàn)實(shí)中我們依然借助一些優(yōu)秀框架,幫助我們做這些轉(zhuǎn)換,這里我們選擇YYModel,它是YYKit中的一個(gè)子項(xiàng)目,可以單獨(dú)使用。
使用 pod 引入,在 Podfile 文件中添加:
pod 'YYModel'
運(yùn)行:
pod update
引入頭文件:
#import <YYModel.h>
首先需要定義對象:
@interface WeatherInfo : NSObject
@property(nonatomic, copy) NSString *city;
@property(nonatomic, copy) NSString *cityid;
@property(nonatomic, copy) NSString *temp;
@property(nonatomic, copy) NSString *WD;
@property(nonatomic, copy) NSString *WS;
@property(nonatomic, copy) NSString *SD;
@property(nonatomic, copy) NSString *WSE;
@property(nonatomic, copy) NSString *time;
@property(nonatomic, copy) NSString *isRadar;
@property(nonatomic, copy) NSString *Radar;
@property(nonatomic, copy) NSString *njd;
@property(nonatomic, copy) NSString *qy;
@property(nonatomic, copy) NSString *rain;
@end
屬性名與 json 字段保持一致,這樣才能正確轉(zhuǎn)換。
接著,用 AFNetworking 請求網(wǎng)絡(luò)接口:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/html",nil];
[manager GET:@"http://www.weather.com.cn/data/sk/101010100.html"
parameters:nil
progress:nil
success:^(NSURLSessionDataTask * _Nonnull task,
id _Nullable responseObject) {
NSLog(@"%@", responseObject);
WeatherInfo *weather = [WeatherInfo yy_modelWithDictionary:responseObject[@"weatherinfo"]];
NSLog(@"%@", weather);
}
failure:^(NSURLSessionDataTask * _Nullable task,
NSError * _Nonnull error) {
}];
關(guān)鍵是WeatherInfo *weather = [WeatherInfo yy_modelWithDictionary:responseObject[@"weatherinfo"]];,直接將 json(這里是字典)轉(zhuǎn)成了 WeatherInfo 對象。
有些時(shí)候網(wǎng)絡(luò)返回的字段名不符合 OC 代碼規(guī)范,YYModel 也很貼心的提供了解決方案:
#import "WeatherInfo.h"
@implementation WeatherInfo
+ (NSDictionary *)modelCustomPropertyMapper {
return @{@"windDirection" : @"WD"};
}
@end
通過實(shí)現(xiàn) modelCustomPropertyMapper 方法,我們可以手動指定轉(zhuǎn)換后的屬性名稱。
這樣,現(xiàn)實(shí)開發(fā)中的大部分網(wǎng)絡(luò)請求都可以自動完成了,最后,通過 ModelMaker 工具,可以自動將 json 轉(zhuǎn)換成對象聲明:

下載地址:
https://pan.baidu.com/s/1slEss13
解壓密碼:xishiios