在 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/