我正在使用 RestKit 2.0 使用“multipartFormRequestWithObject”方法将核心数据实体和图像发送到服务器。但是,当实体数据到达时,它不是 json 格式。如果我使用没有图像的“postObject”发送实体,则数据为 json 格式。我对这两种情况都使用相同的 RKObjectMapping。我需要做什么才能使对象序列化为 json?我试过了
[request setValue:@"application/json" forHTTPHeaderField:@"content-type"];
但这并没有帮助,我已经有了我的对象管理器设置:
[objectManager setRequestSerializationMIMEType:RKMIMETypeJSON];
[objectManager setAcceptHeaderWithMIMEType:RKMIMETypeJSON];
我的 Header Content-Type 是 multipart/form-data 但我想这是必需的。
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)";
}
我的完整代码用于映射和操作如下。像往常一样,任何反馈都会很棒。谢谢。铝
- (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];
}