实际项目开发中会用到的接口多种多样,有一些相对复杂的数据例如:列表、列表嵌套等,这里使用一个真实案例来阐述如何解决
使用GET请求调用API(https://www.sojson.com/open/api/weather/json.shtml),获取“北京市”未来五天天气预报
用浏览器打开该API,可以看到JSON数据格式,最终显示效果如图所示
先建模:
@interface WeatherModel : BaseModel
@property (nonatomic, strong) NSString *aqi;//161
@property (nonatomic, strong) NSString *date;//19日星期四
@property (nonatomic, strong) NSString *sunrise;//05:33
@property (nonatomic, strong) NSString *sunset;//18:56
@property (nonatomic, strong) NSString *high;//高温 26.0℃
@property (nonatomic, strong) NSString *low;//低温 13.0℃
@property (nonatomic, strong) NSString *type;//多云
@property (nonatomic, strong) NSString *fx;//东南风
@property (nonatomic, strong) NSString *fl;//4-5级
@property (nonatomic, strong) NSString *notice;//阴晴之间,谨防紫外线侵扰
@end
外面一层数据在建模时,需要注意一下其中forecast和yesterday字段对应的类型定义,其中yesterday是WeatherModel类型,forecast数组的每项元素也是WeatherModel类型
@interface CityWeatherModel : BaseModel
@property (nonatomic, strong) NSString *shidu;//73%
@property (nonatomic, strong) NSString *wendu;//17
@property (nonatomic, strong) NSString *pm25;//150
@property (nonatomic, strong) NSString *pm10;//232
@property (nonatomic, strong) NSString *quality;//中度污染
@property (nonatomic, strong) WeatherModel *yesterday;//注意类型
@property (nonatomic, strong) NSArray *forecast;//注意类型
@end
接下来封装业务接口,这里相比第二章中的简单数据解析多了些内容,但是很好理解
- 定义keyArray和valueArray数组,用于映射responseObj内部数据关系
- 从刚才建模的步骤,得知yesterday对象和forecast数组元素类型均为WeatherModel,keyArray中存储数据需要映射的Model类型,valueArray中存储被映射的数据字段
重要:keyArray[0,1,…n]和valueArray[0,1,…n],两数组下标对应的内容必须逐一对应,不可出现元素个数不相等的情况
+ (void)weatherCity:(NSString *)city success:(void(^)(CityWeatherModel *model))success failure:(void(^)(HttpException * e))failure{
NSString *urlStr = @"[https://www.sojson.com/open/api/weather/json.shtml](https://www.sojson.com/open/api/weather/json.shtml)";
NSDictionary *requestDic = @{@"city":city};//入参数据
[HttpClientMgr get:urlStr params:requestDic success:^(id responseObj) {
NSMutableArray *keyArray = [NSMutableArray array];
[keyArray addObject:NSStringFromClass([WeatherModel class])];
[keyArray addObject:NSStringFromClass([WeatherModel class])];
NSMutableArray *valueArray = [NSMutableArray array];
[valueArray addObject:@"yesterday"];
[valueArray addObject:@"forecast"];
CityWeatherModel *model = [CityWeatherModel parse:responseObj ClassArr:keyArray Elements:valueArray]; //NSDictionary -> Model
if(success){
success(model);
}
} failure:^(HttpException *e) {
if(failure){
failure(e);
}
}];
}
调用:
[NetworkAPI weatherCity:@"北京" success:^(CityWeatherModel *model) {
NSArray *dataArr = model.forecast;
} failure:^(HttpException *e) {
}];
如何将数据呈现在界面上这里不再赘述