RestKit 0.20.2路由和映射

时间:2013-06-10 09:36:03

标签: routing restkit-0.20

我还有以下JSON和路由映射。 单项JSON

{
"quantity" : 0,
"id" : 1,
"version" : 0,
"sku" : "sku1",
"title" : "title1",
}

并且所有Items JSON如下: -

[
    {
    "quantity" : 2,
    "id" : 1,
    "version" : 0,
    "sku" : "sku1",
    "title" : "title1",
    },
    {
    "quantity" : 4,
    "id" : 2,
    "version" : 0,
    "sku" : "sku2",
    "title" : "title2",
    }
]

以下是映射: -

RKEntityMapping *newItemMapping = [RKEntityMapping mappingForEntityForName:NSStringFromClass([Item class]) inManagedObjectStore:manager.managedObjectStore];
newItemMapping.identificationAttributes = @[@"id"];
[newItemMapping addAttributeMappingsFromDictionary:@{
        @"id" : @"id",
        @"version" : @"version",
        @"title" : @"title",
        @"sku" : @"sku"
}];

这是路由信息。

[[RKObjectManager sharedManager].router.routeSet addRoute:[RKRoute routeWithClass:[Item class] pathPattern:@"items/:id" method:RKRequestMethodGET]];
[[RKObjectManager sharedManager].router.routeSet addRoute:[RKRoute routeWithClass:[Item class] pathPattern:@"items" method:RKRequestMethodPOST]];
[[RKObjectManager sharedManager].router.routeSet addRoute:[RKRoute routeWithClass:[Item class] pathPattern:@"items/:id" method:RKRequestMethodPUT]];
[[RKObjectManager sharedManager].router.routeSet addRoute:[RKRoute routeWithClass:[Item class] pathPattern:@"items/:id" method:RKRequestMethodDELETE]];

GET请求正常工作,并使用上面的映射正确加载对象。

[[RKObjectManager sharedManager] getObject:sampleItemObject path:nil parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
    RKLogInfo(@"Load collection of Items: %@", mappingResult);
}                                         failure:^(RKObjectRequestOperation *operation, NSError *error) {
    RKLogError(@"Operation failed with error: %@", error);
}];

但POST请求失败,显示如下信息: -

[[RKObjectManager sharedManager] postObject:newItem path:nil parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
    NSLog(@"%@", mappingResult.array);
}                                             failure:^(RKObjectRequestOperation *operation, NSError *error) {
    NSLog(@"Failure saving post: %@", error.localizedDescription);
}];

错误讯息: -

保存帖子失败:预期内容类型{(     “应用程序/ x WWW的形式进行了urlencoded”,     “应用程序/ JSON” )},得到text / html

请协助解决出错的问题?

谢谢, 的FokⅠ

1 个答案:

答案 0 :(得分:2)

在配置共享管理器时或在发出帖子请求之前的某个时刻添加此行:

[RKObjectManager sharedManager].requestSerializationMIMEType = RKMIMETypeJSON;

此外,请确保为对象定义了序列化映射。这些将允许RestKit将对象作为格式正确的JSON字符串发送到服务器。