RestKit对象映射请求,在其HTTP主体中嵌套了JSON

时间:2013-12-04 01:01:09

标签: ios iphone json restkit restkit-0.20

我正在HTTP主体中使用嵌套JSON发出POST请求,但我没有得到相应的响应。我传递一个名为RequestObject的自定义对象,其属性为:

@interface RequestObject : NSObject
@property (nonatomic, copy) NSString *title;
@property (nonatomic, strong) NSDictionary *location;
@property (nonatomic, strong) NSMutableArray *pictures;

我想映射我的对象,以便在其HTTP Body中,JSON看起来像这样:

{
        "title": "Magic School Bus",
        "location": {
            "latitude": "38.764792",
            "longitude": "-121.247574"
        },
        "pictures": [
            {
                "base64pic": "iVBORw0KGg..."
            }
        ]
}

对于请求对象,我将其配置为:

RequestObject *request = [[RequestObject alloc] init];

// Title property
request.title = @"MyTitle";

// Location property
request.location = @{
              @"latitude" : [NSNumber numberWithDouble:38.757965],
              @"longitude" : [NSNumber numberWithDouble:-121.254044]
              };

// Pictures property
request.pictures = [[NSMutableArray alloc] init]; 

// I add a dictionary into the pictures array
NSDictionary *picture = @{@"base64pic" : @"somebase64string"};
[request.pictures addObject:picture];

我相信我可能会错误地设置我的request.pictures,这就是为什么我的回复出错了。这是我调用POST请求的其余代码:

RKObjectMapping *requestMapping = [RKObjectMapping requestMapping];
[mapping addAttributeMappingsFromArray:@[@"title", @"location", @"pictures"]];
[manager addRequestDescriptor:[RKRequestDescriptor requestDescriptorWithMapping:requestMapping objectClass:[RequestObject class] rootKeyPath:nil method:RKRequestMethodPOST]];

RKObjectMapping *responseMapping = [RKObjectMapping mappingForClass:[NSDictionary class]];
[mapping addAttributeMappingsFromArray:@[@"response"]];
[manager addResponseDescriptor:[RKResponseDescriptor responseDescriptorWithMapping:responseMapping method:RKRequestMethodPOST pathPattern:nil keyPath:nil statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];

// Post
[manager postObject:request path:@"books/" parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *result){

    // Response back
}failure:^(RKObjectRequestOperation *operation, NSError *error) {

当我在项目中进行POST调用时,我将其视为控制台中的HTTP Request主体:

Request Body : location[latitude]=38.757965&location[longitude]=-121.254044&pictures[][base64pic]=somebase64string&title=MyTitle

2 个答案:

答案 0 :(得分:0)

您的代码看起来不错。问题似乎是您没有将请求序列化类型设置为JSON,因此您将获得表单URL编码正文。

答案 1 :(得分:0)

您可以使用您的请求数据创建NSMutableURLRequest和setHTTPBody,并使用该请求创建RKObjectRequestOperation。它可以使事情变得更容易和更直接。

下一个问题:   并非所有对象都是有效的JSOn对象,并且您只能将有效的JSON对象与请求主体一起传递,否则服务器端可能无法对其进行解密(服务器端将不会知道您的自定义对象)。