3

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

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

所有项目 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);
}];

错误信息:-

保存帖子失败:预期的内容类型 {( "application/x-www-form-urlencoded", "application/json" )}, got text/html

请协助解决任何问题?

谢谢,福基

4

1 回答 1

2

Add this line when you configure your shared manager or at some point before you make the post request:

[RKObjectManager sharedManager].requestSerializationMIMEType = RKMIMETypeJSON;

Also, make sure you have a serialization mapping defined for your object. These will allow RestKit to send the object to the server as a properly formatted JSON string.

于 2013-06-12T13:55:44.613 回答