我正在使用ASIHTTPRequest和json-framework将JSON发布到rails应用程序,
问题是,当JSON到达服务器时,它用双引号括起来,
以下是我用来编码和发送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 setRequestMethod:@"POST"];
[request setDelegate:self];
[request setDidFinishSelector:@selector(requestDone:)];
[request setDidFailSelector:@selector(requestWentWrong:)];
[queue addOperation:request];
正确记录为:
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
虽然当它到达服务器时它输出为:
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"
如何将数组作为单个字符串包裹起来?
答案 0 :(得分:3)
尝试这种方式:
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];
答案 1 :(得分:0)
我通过手动创建JSON字符串解决了这个问题:
NSString *dataString = [NSString stringWithFormat:@"{\"shared_items\":%@,\"shared_list\":%@,\"facebook_id\":%@}",[sharedItems JSONRepresentation],[sharedList JSONRepresentation],facebookID];