我需要通过 POST 将以下 JSON数组发送到我们的服务器:
task:{"id":"123","list":"456","done":1,"done_date":1305016383}
我尝试使用 JSON库,但我在某种程度上愚蠢地使用它。我甚至试图自己建立POST-String,但也失败了:
NSString *post = @"task='{id:123,list:456,done:1,done_date:1305016383}'";
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:30];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[post dataUsingEncoding:NSUTF8StringEncoding]];
....
你能帮帮我吗? json'ed POST字符串对我来说足够了:))
答案 0 :(得分:1)
所以这可能是您要问的问题,也可能不是,但您的JSON字符串形式不正确。 JSON格式的“任务”数组如下所示:
NSString *post = @"{"task":[{"id":"123","list":"456","done":1,"done_date":1305016383}]}";
我只是在尝试将类似的情况发布到PHP服务器上,我在网上找不到任何关于它的问题,但如果我发布相同的数据,这就是我不得不做的事情:
NSString *post = @"task[0][id]=123&task[0][list]=456&task[0][done]=1&task[0][done_date]=1305016383&";
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:30];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:[post dataUsingEncoding:NSUTF8StringEncoding]];
...
祝你好运!
答案 1 :(得分:1)
这就是我处理它的方式:
-(void)imageFactory:(NSDictionary*)postJSON
{
// Convert the JSON string to Data to be sent.
NSData* postData = [[postJSON JSONRepresentation] dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[URLManager imageFactory]]];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"%d", [postData length]] forHTTPHeaderField:@"Content-Length"];
// IMPORTANT MAKE SURE YOU ADD THIS LINE SO THE SERVER KNOWS WHAT ITS GETTING
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
// Add some nice handlers so you know what you got from the server
NSURLResponse* response;
NSHTTPURLResponse* httpResponse;
NSError* error;
NSData* responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString* stringResponse = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
httpResponse = (NSHTTPURLResponse*) response;
int statuscode = [httpResponse statusCode];
if (statuscode == 200)
{
log4Debug(@"ImageFactory Response Successful, Retrieving image");
// Handle the response here if needed
}
else
{
log4Error(@"ImageFactory Response Failed: %@", stringResponse);
// Show some form of alert here if needed
}
// release all objects saved to memory
[request release];
request = nil;
[stringResponse release];
stringResponse = nil;
}
我的json是一个看起来像这样的字符串 {“user”:1337,“title”:“some title”,“itemKeys”:[1,1,1,1,1]}
答案 2 :(得分:0)
我认为问题不在于方法,而在于您尝试发布的字符串。试试这个:
NSString *post = @"\"task\":{\"id\":\"123\",\"list\":\"456\",\"done\":1,\"done_date\":1305016383}";
换句话说:用引号进行试验。
您使用的是什么JSON库?