JSONModel中的嵌套字典

时间:2014-03-07 19:54:50

标签: ios objective-c json nsdictionary jsonmodel

创建JSONModel时出错。

  

Error Domain = JSONModelErrorDomain Code = 1“无效的JSON数据:尝试使用initWithDictionary初始化JSONModel对象:错误:但字典参数不是'NSDictionary'。” UserInfo = 0x9bc2340 {kJSONModelKeyPath = categories.Data,NSLocalizedDescription =无效的JSON数据:尝试使用initWithDictionary初始化JSONModel对象:错误:但字典参数不是'NSDictionary'。}

这是我得到的回应......

{
    "categories": {
        "Data": [
            {
                "Id": 19,
                "Name": "",
                "Description": "",
                "ImageURL": "",
                "FullSizeImageUrl": "",
                "ParentCategoryId": 0
            }
        ],
        "Total": 1
    }
}

以下是我的模特

@interface CategoryResponse : JSONModel
@property (strong, nonatomic) NSDictionary <Categories> *categories;
@end

@protocol Categories @end
@interface Categories : JSONModel
@property (assign, nonatomic) int Total;
@property (strong, nonatomic) NSArray<CategoryData> *Data;
@end

@protocol CategoryData @end
@interface CategoryData : JSONModel
@property (strong, nonatomic) NSString <Optional> *Name;
@property (strong, nonatomic) NSString <Optional> *Description;
@property (strong, nonatomic) NSString <Optional> *ImageURL;
@property (strong, nonatomic) NSString <Optional> *FullSizeImageUrl;
@property (assign, nonatomic) int Id;
@property (assign, nonatomic) int ParentCategoryId;

void (^success)(AFHTTPRequestOperation *, id) = ^(AFHTTPRequestOperation *op, id data) {
    NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    NSError *error;

    categories = [[CategoryResponse alloc] initWithString:responseString error:&error];

    complete(nil, categories);
};

我意识到@property (strong, nonatomic) NSDictionary <Categories> *categories;不是这样做的正确方法,但我不知道是什么。

1 个答案:

答案 0 :(得分:-1)

我想你可以这样处理你的字典的分配:

void (^success)(AFHTTPRequestOperation *, id) = ^(AFHTTPRequestOperation *op, id data) {
    categories = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

    complete(nil, categories);
};

虽然我不熟悉AFNetworking,因为我喜欢使用NSURLConnection。