ios - 如何在ios中使用nsmutableurlrequest发送递归json请求?

标签 ios xcode json api nsmutableurlrequest

在 iOS 中创建这个

"{
"email":string, 
"password":string
}"

json 请求正文,我传递从字符串创建的 nsdata

email=myname@domain.com&password=mypassword

到 NSMutableURLRequest 的 setHTTPBody 方法。这工作得很好,我对此还可以。

但是如果我想创建这个怎么办

"{
"post":
       {
        "title":string,
        "room_id":int,
        "content":string,
       }
}"

json 请求体?我尝试做一些字符串组合来解决这个递归,但并没有真正解决。我还检查了 NSMutableURLRequest 的方法,但找不到与解决此问题相关的内容。

编辑:

这会创建帖子,因为它应该很好,但对于递归情况,我需要相当于字符串 email=myname@domain.com&password=mypassword 。当我按应有的方式发送数据时,它不起作用。当我作为我提供的字符串发送时,它可以工作。

NSString *usertoken =  [appDelegate token];
NSString *posttopic = @"111testtopic";
NSString *postbody =  @"111testbody";

NSDictionary *dict = @{@"post":@{@"title":posttopic,@"room_id":@"246",@"content":postbody}};
NSData *body = [NSJSONSerialization dataWithJSONObject:dict
                                               options:NSJSONWritingPrettyPrinted
                                                 error:nil];



NSString *postLength = [NSString stringWithFormat:@"%d", [body length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

//send the post
NSString *urlstring = [NSString stringWithFormat:@"http://mydomain.com/posts.json?auth_token=%@", usertoken];
[request setURL:[NSURL URLWithString:urlstring]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:body];



NSURLResponse *response;
NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];

最佳答案

试试这个

NSDictionary *dict = @{@"post":@{@"title":string,@"room_id":int,@"content":string}};
NSData *body = [NSJSONSerialization dataWithJSONObject:dict 
                                               options:NSJSONWritingPrettyPrinted 
                                                 error:&error];

这个想法是使用一些嵌套字典来描述你的 json 并序列化它们以使你的 jsonData 传递给请求。

关于ios - 如何在ios中使用nsmutableurlrequest发送递归json请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14736442/

相关文章:

json - 在 TabBarController 中共享 JSON 数据以查看 Controller

json - 在 bash 的特定 JSON 字段中查找最高值

iOS 容器 View Controller - 为什么transitionFromViewController需要fromViewController?

iphone - XCode:从plist读取数据到NSmutablearray

ios - Firebase 按属性名称查询一个特定对象

xcode - 使用按钮将行添加到 TableView

ios - 如何通过命令行将Xcode项目构建和部署到新的Apple的TestFlight

ios - 音频编解码器加密

ruby-on-rails - 帮助在 Lion GM 上安装 Ruby 1.9.2

javascript - Ajax/Json 错误 : "A circular reference was detected while serializing an object of type" when trying to bring a list