ASIHTTPRequest wrapping JSON in quotes
I'm using ASIHTTPRequest and json-framework to post JSON to a rails app,
The problem is that when the JSON arrives on the server it is wrapped in double quotes,
Here is the code i am using to encode and send the JSON:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/shared_lists.json",kAPIRoot]]];
NSString *dataString = [NSString stringWithFormat:@"shared_items=%@&shared_list=%@&facebook_id=%@",[sharedItems JSONRepresentation],[sharedList JSONRepresentation],facebookID];
NSLog(@"%@",[NSString stringWithUTF8String:[[dataString dataUsingEncoding:NSUTF8StringEncoding] bytes]]);
[request appendPostData:[dataString dataUsingEncoding:NSUTF8StringEncoding]];
[request setRequestMetho开发者_开发知识库d:@"POST"];
[request setDelegate:self];
[request setDidFinishSelector:@selector(requestDone:)];
[request setDidFailSelector:@selector(requestWentWrong:)];
[queue addOperation:request];
Which logs correctly as:
shared_items=[{"entity_id":"531","position":"1"},{"entity_id":"733","position":"2"},{"entity_id":"723","position":"3"},{"entity_id":"2530","position":"4"}]&shared_list={"list_id":1197}&facebook_id=-1540981104
Although when it arrives on the server it outputs as:
shared_items="[{"entity_id":"531","position":"1"},{"entity_id":"733","position":"2"},{"entity_id":"723","position":"3"},{"entity_id":"2530","position":"4"}]",shared_list="{"list_id":1197}",facebook_id="-1540981104"
How do i stop the arrays being wrapped up as a single string?
Try this way:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/shared_lists.json",kAPIRoot]]];
NSString *dataString = [NSString stringWithFormat:@"shared_items=%@&shared_list=%@&facebook_id=%@",[sharedItems JSONRepresentation],[sharedList JSONRepresentation],facebookID];
NSMutableData *requestBody = [[NSMutableData alloc] initWithData:[dataString dataUsingEncoding:NSUTF8StringEncoding]];
[request setRequestMethod:@"POST"];
[request setPostBody:requestBody];
[request addRequestHeader:@"Content-Type" value:@"application/json; encoding=utf-8"];
[request setUseSessionPersistence:NO];
[request setUseCookiePersistence:NO];
[request setCacheStoragePolicy:ASICacheForSessionDurationCacheStoragePolicy];
I solved the problem by manually creating the JSON String like so:
NSString *dataString = [NSString stringWithFormat:@"{\"shared_items\":%@,\"shared_list\":%@,\"facebook_id\":%@}",[sharedItems JSONRepresentation],[sharedList JSONRepresentation],facebookID];
精彩评论