我有一个请求给了我两部分数据,json看起来像这样
{
"banner_content":
[
{
"activi_id":"1",
"activi_pic":
},
{
"activi_id":"2",
"activi_pic":
},
],
"categories":
[
{...},
{...},
]
}
当我写responseDescriptor
来映射数据时,我发现我必须定义一个包含banner_content
数组和categories
数组的模型(我不想)
或者我必须编写两个responseDescriptors,当请求完成时,我必须从(RKMappingResult *)mappingResult
获取两部分数据
然后得到像[mappingResult objectForKey:@"banner_content"]
和[mappingResult objectForKey:@"categories"]
这样的数组
这很奇怪
下面是我的代码 文件:RCategory.m
@implementation RCategory
+ (NSDictionary *)_mapping {
return @{@"title" : @"title"};
}
+ (RKObjectMapping *)mapping {
// Setup our object mappings
RKObjectMapping *categoryMapping = [RKObjectMapping mappingForClass:[self class]];
[categoryMapping addAttributeMappingsFromDictionary:[[self class] _mapping]];
RKObjectMapping *itemMapping = [RCategoryItem mapping];
RKRelationshipMapping* relationShipMapping = [RKRelationshipMapping relationshipMappingFromKeyPath:@"content"
toKeyPath:@"items"
withMapping:itemMapping];
[categoryMapping addPropertyMapping:relationShipMapping];
return categoryMapping;
}
@end
文件:RAd.m忽略
文件:viewController.m
- (void)loadCategory {
// Load the object model via RestKit
RKObjectManager *objectManager = [RKObjectManager sharedManager];
RKObjectMapping *categoryMapping = [RCategory mapping];
RKResponseDescriptor *categoryResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:categoryMapping
method:RKRequestMethodGET
pathPattern:nil
keyPath:@"category"
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
RKObjectMapping *adsMapping = [RAd mapping];
RKResponseDescriptor *adResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:adsMapping
method:RKRequestMethodGET
pathPattern:nil
keyPath:@"banner_content"
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
//** DO I MUST ADD TWO RESPONSE_DESCRIPTOR FOR ONE REQUEST??**
[objectManager addResponseDescriptor:categoryResponseDescriptor];
[objectManager addResponseDescriptor:adResponseDescriptor];
[objectManager getObjectsAtPath:RPATH(CATEGORY_PATH)
parameters:nil
success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
NSArray* statuses = [mappingResult array];
[self.categories addObjectsFromArray:statuses];
if ([self isViewLoaded]) {
[self.tableView reloadData];
}
}
failure:^(RKObjectRequestOperation *operation, NSError *error) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
NSLog(@"Hit error: %@", error);
}];
}
有没有人有更好的方法来解决我的问题?
顺便说一句,我在模型类中写-mapping
,这是我能想到的最简单,最好的方法
我想知道你是如何编写映射的。
答案 0 :(得分:1)
您需要2个响应描述符,因为响应有2个逻辑上独立的部分。这可以。如果您使用的是Core Data,那么您将不会担心,因为所有对象都只是保存到上下文中,您可以根据需要获取它们。使用对象映射,如果您不关心分组,那么您可以从映射结果中获取所有对象的数组。
从模型对象返回的数据创建映射很好 - 但它确实限制了你,因为每个目标键只能有一个源键。当您使用不同的密钥对同一对象进行不同的响应时会发生什么,这意味着与其他密钥相同(希望您没有,但这一切都取决于服务器API)。