iphone – 使用ASIHTTPRequest使用NSDictionary对嵌套的params进行POST

试图将嵌套参数的信息发布到rails应用程序并遇到一些麻烦.

#pragma mark - Begin Network Operations
- (void)beginNetworkOperation {
    NSURL *requestURL = [NSURL URLWithString:[self retrieveURL]];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:requestURL];

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
    [request setShouldContinueWhenAppEntersBackground:YES];
#endif

    [request setRequestMethod:@"PUT"];

    [request addRequestHeader:@"Content-Type" value:@"application/json"];

    [request addPostValue:strClientId forKey:@"client_id"];
    [request addPostValue:strAccessToken forKey:@"access_token"];

    NSDictionary *assetDictionary = [NSDictionary dictionaryWithObject:self.tags forKey:@"tags"];
    [request addPostValue:assetDictionary forKey:@"asset"];

    [request setDelegate:self];
    [request setDidFinishSelector:@selector(requestFinished:)];
    [request setDidFailSelector:@selector(requestFailed:)];
    [request startSynchronous];
}

self.tags只是一个带有逗号分隔值的NSString,但是一旦到达rails服务器,就无法读取tags参数(params [:asset] [:tags]).

最佳答案
尝试将字典作为JSON字符串而不是字典对象传递给您.

你可以使用iOS5 JSON库或者这个来实现更好的兼容性:

https://github.com/stig/json-framework

我所做的是使用appendPostData,因为我很确定设置标头(addRequestHeader)和使用addPostValue是不兼容的功能.
这是我的代码示例:

ASIFormDataRequest *request;
[request addRequestHeader:@"Content-Type" value:@"application/json"];
[request appendPostData:[[SBJsonWriter new] dataWithObject:myDictionaryToPassAsAnArgument]];

使用appendPostData时,不能使用任何addPostValue.你必须将所有内容都放在字典中.

转载注明原文:iphone – 使用ASIHTTPRequest使用NSDictionary对嵌套的params进行POST - 代码日志