JsonModel无法将json中的数组转换为jsonmodel继承的类

时间:2016-08-26 13:37:01

标签: ios objective-c afnetworking-3 jsonmodel

我已将我的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数组。

为什么会发生这种情况,我怎样才能拥有自定义类的数组?

1 个答案:

答案 0 :(得分:0)

不,如果要访问PTPDestination类属性,JSON模型还将数组转换为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&#34;数据&#34;来自网络响应

PTPIndex *ptpInd = [[PTPIndex alloc] initWithDictionary:data error:&error];

找到PTPDestination的总数并在循环中运行。 您可以像这样访问对象。

PTPDestination *ptpdest = [ptpInd PTPDestination[0]];