我已将我的api结果建模如下:
#import "PTPDestination.h"
@interface PTPIndex : PTPBaseEntity
@property (strong, nonatomic) NSNumber * citiesCount;
@property (strong, nonatomic) NSNumber * hotelsCount;
@property (strong, nonatomic) NSArray<PTPDestination *> * top_destinations;
@end
我还像这样建模PTPDestination:
@interface PTPDestination : PTPBaseEntity
@property (assign, nonatomic) NSNumber * id;
@property (assign, nonatomic) NSNumber * min_price;
@property (assign, nonatomic) NSNumber * max_discount;
@property (assign, nonatomic) NSString * title;
@end
我用AFNetworking这样称呼我的api:
AFHTTPSessionManager * manager = [self createAPISessionManager];
[manager GET:[self createServiceUrlWithMethod:@"someURL"] parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSError * error = nil;
PTPIndex * index = [[PTPIndex alloc] initWithDictionary:responseObject error:&error];
if (error) {
callback (nil, [PTPApiCenteralizedErrorHandler getErrorFromApiError:error task:task responseObject:responseObject]);
return;
}
callback (index, nil);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
callback (nil, [PTPApiCenteralizedErrorHandler getErrorFromApiError:error task:task]);
}];
问题在于一系列目的地。我不知道为什么数组没有转换为PTPDestination对象,它仍然是一个NSDictionaries数组。
为什么会发生这种情况,我如何拥有自定义类的数组呢?
否,JSON模型如果要访问PTPDestination类属性,还将数组转换为JSONObject。
PTPIndex类
#import "JSONModel.h"
@interface PTPIndex : JSONModel
@property (strong, nonatomic) NSNumber * citiesCount;
@property (strong, nonatomic) NSNumber * hotelsCount;
@property (strong, nonatomic) NSArray<PTPDestination *> * top_destinations;
@end
PPTPDestination类
#import "JSONModel.h"
@interface PTPDestination : JSONModel
@property (assign, nonatomic) NSNumber * id;
@property (assign, nonatomic) NSNumber * min_price;
@property (assign, nonatomic) NSNumber * max_discount;
@property (assign, nonatomic) NSString * title;
@end
NSDictionary来自网络响应的“数据”
PTPIndex *ptpInd = [[PTPIndex alloc] initWithDictionary:data error:&error];
找到PTPDestination的总数并在循环中运行。您可以像这样访问对象。
PTPDestination *ptpdest = [ptpInd PTPDestination[0]];