RestKit ios - put - json而不是表单编码

时间:2022-05-22 08:13:36

i am writing an ios app that uses restkit to communicate with a web server through Rest with JSON

我正在编写一个ios应用程序,它使用restkit通过Rest with JSON与Web服务器进行通信

i am able to use [[RKObjectManager sharedManager] loadObjectsAtResourcePath:path delegate:self] to get object from my web service as JSON, map it to obj-c object, it works fine

我能够使用[[RKObjectManager sharedManager] loadObjectsAtResourcePath:path delegate:self]从我的Web服务获取对象作为JSON,将其映射到obj-c对象,它工作正常

now i am trying to use: [[RKObjectManager sharedManager] putObject:obj delegate:self]; and this call sends an object to the web service as form encoded and not JSON

现在我正在尝试使用:[[RKObjectManager sharedManager] putObject:obj delegate:self];并且此调用将对象作为编码的表单发送到Web服务,而不是JSON

so my question is: how to configure the sharedManager (or the routeur?) to send with content type JSON instead of form encoded.

所以我的问题是:如何配置sharedManager(或routeur?)发送内容类型JSON而不是表单编码。

any code example much appreciated.

任何代码示例非常感谢。

Thx!

谢谢!

5 个解决方案

#1


9  

The easiest way is to simply set the property when you initialize the object manager, like so:

最简单的方法是在初始化对象管理器时简单地设置属性,如下所示:

RKObjectManager* objectManager = [RKObjectManager objectManagerWithBaseURL:@"http://url.com"];
objectManager.serializationMIMEType = RKMIMETypeJSON;

#2


3  

Evan is correct, but I've had to also make sure I am sending a JSON string, because I had a nested NSDictionay.

Evan是正确的,但我还必须确保我发送一个JSON字符串,因为我有一个嵌套的NSDictionay。

If you have a dictionary you want to send as a JSON string, here's how you can do it:

如果您要将字典作为JSON字符串发送,请按以下步骤操作:

// create a JSON string from your NSDictionary
NSError *error; 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict 
                                                   options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                     error:&error];
NSString *jsonString = [[NSString alloc] init];
if (!jsonData) {
    NSLog(@"Got an error: %@", error);
} else {
    jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

// make the post using the objectManager if you want to map the response to a model
RKObjectManager* objectManager = [RKObjectManager sharedManager];  
[objectManager loadObjectsAtResourcePath:@"/api/" delegate:self block:^(RKObjectLoader* loader) {
    loader.serializationMIMEType = RKMIMETypeJSON; // We want to send this request as JSON
    loader.objectMapping = [objectManager.mappingProvider objectMappingForClass:[Plan class]];
    loader.resourcePath = @"/api/";
    loader.method = RKRequestMethodPOST;
    loader.params = [RKRequestSerialization serializationWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] MIMEType:RKMIMETypeJSON];
}];

#3


1  

Okay just found how to do it:

好的,只是发现了如何做到这一点:

subclass RKRouter.h or just change in RKDynamicRouter.m

子类RKRouter.h或只是更改RKDynamicRouter.m

return [object propertiesForSerialization];

to

[RKJSONSerialization JSONSerializationWithObject:[object propertiesForSerialization]];

and RestKit generate JSON for putObject call

和RestKit为putObject调用生成JSON

#4


1  

Create an Object Manager and set the property for matching the header in JSON format

创建对象管理器并设置属性以匹配JSON格式的标头

RKObjectManager *objectManager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:@"http://mobile.com"]];
[objectManager addResponseDescriptorsFromArray:@[responseDescriptor]];

objectManager.requestSerializationMIMEType = RKMIMETypeJSON;

#5


0  

You can change serializationMIMEType for individual requests by subclassing RKObjectManager and change implementation of requestWithObject:method:path:parameters: in subclassed manager.

您可以通过继承RKObjectManager并更改requestWithObject:method:path:parameters:在子类管理器中的实现来更改单个请求的serializationMIMEType。

Send request:

发送请求:

SubclassedObjectManager *manager = ...
[manager putObject:nil
           path:pathString
     parameters:parameters
        success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
      } failure:^(RKObjectRequestOperation *operation, NSError *error) {
      }
 ];

Modify MIMEType of request for PUT method:

修改PUT方法请求的MIMEType:

- (NSMutableURLRequest *)requestWithObject:(id)object method:(RKRequestMethod)method path:(NSString *)path parameters:(NSDictionary *)parameters
{
  NSMutableURLRequest *request = [super requestWithObject:object method:method path:path parameters:parameters];
  if (method&RKRequestMethodPUT) {
    NSError *error = nil;
    NSData *serializedJSON = [RKMIMETypeSerialization dataFromObject:parameters MIMEType:RKMIMETypeJSON error:&error];
    [request setValue:RKMIMETypeJSON forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:serializedJSON];
  }

  return request;
}

#1


9  

The easiest way is to simply set the property when you initialize the object manager, like so:

最简单的方法是在初始化对象管理器时简单地设置属性,如下所示:

RKObjectManager* objectManager = [RKObjectManager objectManagerWithBaseURL:@"http://url.com"];
objectManager.serializationMIMEType = RKMIMETypeJSON;

#2


3  

Evan is correct, but I've had to also make sure I am sending a JSON string, because I had a nested NSDictionay.

Evan是正确的,但我还必须确保我发送一个JSON字符串,因为我有一个嵌套的NSDictionay。

If you have a dictionary you want to send as a JSON string, here's how you can do it:

如果您要将字典作为JSON字符串发送,请按以下步骤操作:

// create a JSON string from your NSDictionary
NSError *error; 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict 
                                                   options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                     error:&error];
NSString *jsonString = [[NSString alloc] init];
if (!jsonData) {
    NSLog(@"Got an error: %@", error);
} else {
    jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

// make the post using the objectManager if you want to map the response to a model
RKObjectManager* objectManager = [RKObjectManager sharedManager];  
[objectManager loadObjectsAtResourcePath:@"/api/" delegate:self block:^(RKObjectLoader* loader) {
    loader.serializationMIMEType = RKMIMETypeJSON; // We want to send this request as JSON
    loader.objectMapping = [objectManager.mappingProvider objectMappingForClass:[Plan class]];
    loader.resourcePath = @"/api/";
    loader.method = RKRequestMethodPOST;
    loader.params = [RKRequestSerialization serializationWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] MIMEType:RKMIMETypeJSON];
}];

#3


1  

Okay just found how to do it:

好的,只是发现了如何做到这一点:

subclass RKRouter.h or just change in RKDynamicRouter.m

子类RKRouter.h或只是更改RKDynamicRouter.m

return [object propertiesForSerialization];

to

[RKJSONSerialization JSONSerializationWithObject:[object propertiesForSerialization]];

and RestKit generate JSON for putObject call

和RestKit为putObject调用生成JSON

#4


1  

Create an Object Manager and set the property for matching the header in JSON format

创建对象管理器并设置属性以匹配JSON格式的标头

RKObjectManager *objectManager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:@"http://mobile.com"]];
[objectManager addResponseDescriptorsFromArray:@[responseDescriptor]];

objectManager.requestSerializationMIMEType = RKMIMETypeJSON;

#5


0  

You can change serializationMIMEType for individual requests by subclassing RKObjectManager and change implementation of requestWithObject:method:path:parameters: in subclassed manager.

您可以通过继承RKObjectManager并更改requestWithObject:method:path:parameters:在子类管理器中的实现来更改单个请求的serializationMIMEType。

Send request:

发送请求:

SubclassedObjectManager *manager = ...
[manager putObject:nil
           path:pathString
     parameters:parameters
        success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
      } failure:^(RKObjectRequestOperation *operation, NSError *error) {
      }
 ];

Modify MIMEType of request for PUT method:

修改PUT方法请求的MIMEType:

- (NSMutableURLRequest *)requestWithObject:(id)object method:(RKRequestMethod)method path:(NSString *)path parameters:(NSDictionary *)parameters
{
  NSMutableURLRequest *request = [super requestWithObject:object method:method path:path parameters:parameters];
  if (method&RKRequestMethodPUT) {
    NSError *error = nil;
    NSData *serializedJSON = [RKMIMETypeSerialization dataFromObject:parameters MIMEType:RKMIMETypeJSON error:&error];
    [request setValue:RKMIMETypeJSON forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:serializedJSON];
  }

  return request;
}