【问题标题】:JsonModel cannot convert an array in json to jsonmodel inherited classJsonModel 无法将 json 中的数组转换为 jsonmodel 继承类
【发布时间】:2016-08-26 13:37:01
【问题描述】:

我将我的 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 有效负载的示例吗?
  • @CraigOtis 我称之为网址 ==> www.pintapin.com/service/index/mobile
  • PTPBaseEntity 看起来像什么?它是否也扩展了JSONModel
  • @CraigOtis 是的。它扩展了 JSONModel 类。

标签: ios objective-c afnetworking-3 jsonmodel


【解决方案1】:

不,如果您想访问 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“数据”

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多