RESTKIT响应只有映射结果字典或阵列中的第一个KVC
问题描述:
我在这里有点新,这将是我的第一个问题, 任何提示将不胜感激。RESTKIT响应只有映射结果字典或阵列中的第一个KVC
林收到一本字典从我restkit请求作为回应,但只有其中一个值都包括在内,我错过了一堆KV的从我的JSON,
我做错了?
从API杰森响应:
{"categories" : [
{
"status" : 1,
"rest_id" : 1,
"id" : 1,
"title" : "01. BasicC",
"description" : "basic description"
},
{
"status" : 1,
"rest_id" : 1,
"id" : 26,
"title" : "01. Deli",
"description" : "deli description"
}
]}
IOS函数请求:
- (void)loadProduct{
_categoriesDic=[[NSDictionary alloc]init];
RKObjectMapping* productMapping = [RKObjectMapping mappingForClass:[ProductCategory class]];
[productMapping addAttributeMappingsFromDictionary:@{
@"id": @"id",
@"rest_id": @"rest_id",
@"title": @"title",
@"description": @"description",
@"status":@"status"
}];
RKLogConfigureByName("RestKit/Network", RKLogLevelTrace);
RKLogConfigureByName("RestKit/ObjectMapping", RKLogLevelTrace);
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:productMapping method:RKRequestMethodPOST pathPattern:nil keyPath:@"categories" statusCodes:[NSIndexSet indexSetWithIndex:200]];
RKObjectManager *objectManager = [[RKObjectManager alloc] init];
[objectManager addResponseDescriptor:responseDescriptor];
NSString *jsonRequest = [NSString stringWithFormat:@"id=1"];
NSURL *url=[NSURL URLWithString:@"http://example.com/REST/v2/productCategories"];
NSData *json_data = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody: json_data];
RKObjectRequestOperation *objectRequestOperation = [[RKObjectRequestOperation alloc] initWithRequest:request responseDescriptors:@[ responseDescriptor ]];
[objectRequestOperation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
RKLogInfo(@"Load collection of Categories: %@", mappingResult.dictionary);
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
RKLogError(@"Operation failed with error: %@", error);
}];
[objectRequestOperation start];
}
响应:
Load collection of Categories: {
categories = (
"basic description",
"deli description"
);
}
答
当你的代码做一些稍微奇怪的事情(如创建一个空不可变的字典,并且POST到一个应该使用GET的端点),它似乎工作。看起来你只是不完全理解响应,这是因为你无意中覆盖了内置的方法。
您显示该日志包含:
{
categories = (
"basic description",
"deli description"
);
}
是含有1个键(类),它是2个对象的数组字典的description
。现在,这两个对象也会调用其方法description
以生成日志内容。不幸的是,你有一个名为description
的属性,因此它被访问而不是超类的实现,因此你只是得到了描述。
现在,这并不意味着映射没有奏效,只是日志有误导性。
您应该将目标对象上的description
更改为另一个名称,如overview
,然后您的日志将变得有意义(并且将来您不会看到类似的问题)。
Thnx很多Wain, 这真的帮了我, 所以你说我应该做GET而不是POST从我的API检索数据? 我认为这可能是一个好主意,让参数在帖子正文中设置,而不是使用参数?=在url中, 您是否恰好为我的案例提供了一个很好的示例? thnx再次, – mamadoo 2014-11-03 14:47:56
我说当你调用'.../v2/productCategories'时,我希望你正在做一个GET来收集数据和POST来更新现有的产品类别。事实上,我认为端点是'.../v2/productCategory'。它不一定是这样,它只是一个关于RESTful和接近你试图成为的“规范”的问题。您可能对http://martinfowler.com/articles/richardsonMaturityModel.html感兴趣 – Wain 2014-11-03 15:20:40