Restkit : multipartFormRequestWithObject not json

╄→尐↘猪︶ㄣ 提交于 2019-12-11 08:37:30

问题


I am using RestKit 2.0 to send a core data entity and an image to a server with the 'multipartFormRequestWithObject' method. However, when the entity data arrives it is not in json format. If I send the entity using 'postObject' without an image then the data is in json format. I use the same RKObjectMapping for both situations. What do I have to do to make the Object serialize to json? I tried

[request setValue:@"application/json" forHTTPHeaderField:@"content-type"]; 

But that didn't help and I already have my object manager settings as so:

[objectManager setRequestSerializationMIMEType:RKMIMETypeJSON];
[objectManager setAcceptHeaderWithMIMEType:RKMIMETypeJSON];

My Header Content-Type is multipart/form-data but I guess that is required.

request.headers={
Accept = "application/json";
"Accept-Language" = "en;q=1, fr;q=0.9, de;q=0.8, zh-Hans;q=0.7, zh-Hant;q=0.6, ja;q=0.5";
"Accept-Version" = 1;
"Content-Length" = 19014;
"Content-Type" = "multipart/form-data; boundary=Boundary+0xAbCdEfGbOuNdArY";
"User-Agent" = "app/1.0 (iPhone Simulator; iOS 7.0; Scale/2.00)";

}

My complete code is for the mapping and operation are below. As usual any feedback would be great. Thanks. Al

- (void)loginMainUser:(NSDictionary*)paramsDict path:(NSString *)apiPath{

RKObjectManager *manager = [RKObjectManager sharedManager];

// Response Mapping
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[self class]];
[mapping addAttributeMappingsFromDictionary:@{@"token" : @"token",
                                              @"_links" : @"links"}];

[manager addResponseDescriptorsFromArray:@[[RKResponseDescriptor responseDescriptorWithMapping:mapping
                                                                                        method:RKRequestMethodAny
                                                                                   pathPattern:nil
                                                                                       keyPath:nil
                                                                                   statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)]]];
// Request Mapping
RKObjectMapping *userRequestMapping = [RKObjectMapping requestMapping];
[userRequestMapping addAttributeMappingsFromDictionary:@{@"name" : @"first_name",
                                                         @"surname" : @"last_name",
                                                         @"email" : @"email",
                                                         @"password" : @"password"}];

RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:userRequestMapping
                                                                               objectClass:[self class]
                                                                               rootKeyPath:nil
                                                                                    method:RKRequestMethodAny];
[manager addRequestDescriptor:requestDescriptor];


UIImage *image = [UIImage imageNamed:@"logo.png"];

// Serialize the Article attributes then attach a file
NSMutableURLRequest *request = [manager multipartFormRequestWithObject:self
                                                                method:RKRequestMethodPOST
                                                                  path:apiPath
                                                            parameters:nil
                                             constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
                                                 [formData appendPartWithFileData:UIImagePNGRepresentation(image)
                                                                             name:@"logo"
                                                                         fileName:@"logo.png"
                                                                        mimeType:@"image/png"];
                                                                     }];

RKObjectRequestOperation *operation = [manager objectRequestOperationWithRequest:request
                                                                         success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
                                                                             NSLog(@"Success");
                                                                         } failure:^(RKObjectRequestOperation *operation, NSError *error) {
                                                                             NSLog(@"Failed");
                                                                         }];

[manager enqueueObjectRequestOperation:operation];
}

回答1:


multipartFormRequestWithObject is explicitly not JSON. This is by design. It's the HTTP content type that is changed so JSON and multipart form are mutually exclusive.

So, you need to change your mind about what you're trying to achieve.

One option could be to use a mapping operation to create the JSON for your object and then supply that JSON when you call multipartFormRequestWithObject. This would give you a multipart form message being sent with a section of JSON that could be deserialised on the server.




回答2:


It is not the best approach but if you really need to get the JSON from a object with RestKit, you can convert it using this code:

// The object you want to convert
YourObject *object = ...;

// The RestKit descriptor that you want to use to map.
RKRequestDescriptor *requestDescriptorObject = ...;

NSDictionary *parametersForObject;
parametersForObject = [RKObjectParameterization parametersWithObject:object 
                                                   requestDescriptor:requestDescriptorObject 
                                                               error:nil];


NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parametersForObject 
                                                   options:NSJSONWritingPrettyPrinted 
                                                     error:nil];


NSString *jsonString;
if(jsonData) {
    jsonString = [[NSString alloc] initWithData:jsonData 
                                       encoding:NSUTF8StringEncoding];
}

And then with the JSON string you can post it in a multi-part post. It can be done with any method, but as you have already RestKit, you can do it with the library.

For example, at the code of below there is a post of a file and the JSON string (in fact, the JSON data).

 // The RestKit manager
 RKObjectManager *manager = ...;

 // The server endpoint
 NSString *path = ...;

 NSMutableURLRequest *request = [manager multipartFormRequestWithObject:nil method:RKRequestMethodPOST path:path parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
     // Post of the file
     [formData appendPartWithFileData:[NSData dataWithData:self.dataFile]
                                 name:@"file"
                             fileName:filename
                             mimeType:mimetype];

     // Post of the JSON data
     [formData appendPartWithFormData:jsonData name:@"json_data"];
 }];


来源:https://stackoverflow.com/questions/19537036/restkit-multipartformrequestwithobject-not-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!