I seem to have run into a rather trivia 开发者_运维技巧issue that I can't figure out. I am using ASIFormDataRequest for interacting with my Ruby on Rails app. I have a REST API that accepts a User object. I am using JSONKit to get the JSONString from a NSDictionary.
However, when I do a [request setPostValue:[userObj JSONString] forKey:@"user"];
The request on the server side ends up escaping the quotes. Basically,
{"password":"hello","name":"user","email":"user@foo.com"}
TO
"{\"password\":\"hello\",\"name\":\"user\",\"email\":\"user@foo.com\"}"
This ends up confusing rails and it complains of an invalid object. Can I force ASIFormDataRequest to not escape the quotes? I understand this might be an issue with the JSONString itself but I can't figure out a good solution here.
Thanks
This is what worked for me:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
NSDictionary* inner = [[NSDictionary alloc] initWithObjectsAndKeys:username, @"login",password, @"password", nil];
NSDictionary* user = [[NSDictionary alloc] initWithObjectsAndKeys:inner, @"user", nil];
NSMutableData *requestBody = [[NSMutableData alloc] initWithData:[[user JSONString] dataUsingEncoding:NSUTF8StringEncoding]];
[request addRequestHeader:@"Content-Type" value:@"application/json; encoding=utf-8"];
[request addRequestHeader:@"Accept" value:@"application/json"];
[request setRequestMethod:@"POST"];
[request setPostBody:requestBody];
[request startAsynchronous];
It's not usual to mix ASIFormDataRequest and JSON - normally people encode things in the HTML form data format or they encode in JSON format. Not both!
Could you consider using pure JSON in this case? It might well make your life easier. Basically you would use an ASIHTTPRequest instead of an ASIFormDataRequest, and set it up like this:
NSString *postData = [userObj JSONString];
[request addRequestHeader: @"Content-Type" value: @"application/json; charset=utf-8"];
[request appendPostData:[postData dataUsingEncoding:NSUTF8StringEncoding]];
Aside from that, it's not really clear why it's going wrong - can you use something like wireshark to capture the raw text of the http request you're sending and add that to your question?
How are you extracting the JSON data from the form data on the Ruby side?
精彩评论