0

in iOS to create this

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

json request body, i am passing the nsdata that i create from the string

email=myname@domain.com&password=mypassword

to the setHTTPBody method of the NSMutableURLRequest.This works fine im ok with this.

But what if i want to create this

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

json request body? i tried to make some string combinations to solve this recursion but didnt work out really. I also checked the methods of NSMutableURLRequest but i couldnt find something related to solve this.

edit:

This creates the post as it should be its fine, but i need an equivalent to the string email=myname@domain.com&password=mypassword for the recursive case. When i send the data as it should be it does not work. When i send as the string that i provided it works.

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];
onuryilmaz
  • 378
  • 1
  • 4
  • 9

1 Answers1

1

Try this

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

the idea is to use some nested dictionaries to describe your json and serialize them to get your jsonData to pass to the request.

oiledCode
  • 8,589
  • 6
  • 43
  • 59
  • This creates the post as it should be its fine, but i do not provide nsdata obtained from the string – onuryilmaz Feb 07 '13 at 13:27
  • This creates the post as it should be its fine, but i need an equivalent to the string email=myname@domain.com&password=mypassword for the recursive case. When i send the data as it should be it does not work. When i send as the string that i provided it works. – onuryilmaz Feb 07 '13 at 13:34