現(xiàn)實中的網(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": "暫無實況",
"qy": "1011",
"rain": "0"
}
}
json 的格式一般為:
- 對象(object):一個對象以
{
開始,并以}
結(jié)束 - 稱/值(collection):名稱和值之間使用
:
隔開,一般的形式是:
{name:value}
現(xiàn)實中的iOS網(wǎng)絡(luò)請求
因為 iOS 提供的原生框架—— NSURLSession ——提供的方法要求很多底層參數(shù)僧凰,使用不直觀,錯誤處理也不穩(wěn)定,實際開發(fā)中我們都會選擇網(wǎng)絡(luò)框架,AFNetworking 是目前這方面的首選月趟。它不單封裝了 NSURLSession 的請求,還會自動分配請求隊列恢口,并格式化返回值孝宗,把 json 字符串轉(zhuǎn)成 字典「纾總之就是省時省力因妇。
還有空氣般無處不在的對象
iOS開發(fā)中,任何數(shù)據(jù)都是基于OC對象猿诸,那么婚被,問題來了:請求到的 json 數(shù)據(jù)怎么轉(zhuǎn)成可使用的對象呢?
一種實踐是梳虽,自己定義一套APP端要用的對象址芯,再逐個實現(xiàn)從字典轉(zhuǎn)換的方法,每個請求都要自己實現(xiàn)一套怖辆,這個編碼過程麻煩(且重復(fù))不說是复,接口數(shù)量一多,還容易混亂竖螃。
現(xiàn)實中我們依然借助一些優(yōu)秀框架淑廊,幫助我們做這些轉(zhuǎn)換,這里我們選擇YYModel特咆,它是YYKit中的一個子項目季惩,可以單獨使用。
使用 pod 引入腻格,在 Podfile 文件中添加:
pod 'YYModel'
運行:
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 對象。
有些時候網(wǎng)絡(luò)返回的字段名不符合 OC 代碼規(guī)范酬核,YYModel 也很貼心的提供了解決方案:
#import "WeatherInfo.h"
@implementation WeatherInfo
+ (NSDictionary *)modelCustomPropertyMapper {
return @{@"windDirection" : @"WD"};
}
@end
通過實現(xiàn) modelCustomPropertyMapper 方法蜜另,我們可以手動指定轉(zhuǎn)換后的屬性名稱。
這樣嫡意,現(xiàn)實開發(fā)中的大部分網(wǎng)絡(luò)請求都可以自動完成了举瑰,最后,通過 ModelMaker 工具蔬螟,可以自動將 json 轉(zhuǎn)換成對象聲明:
下載地址:
https://pan.baidu.com/s/1slEss13
解壓密碼:xishiios