我想使用 JSON
数据类型通过 POST
方法将在 iOS 上创建的新对象发送到接收服务器。据我所知,在 iOS 中从服务器接收数据时,所有 JSON
处理都由 Apple 在 iOS 5 中进行了简化。但与 GETting JSON 对象不同,在我能找到的任何地方都没有真正描述发布这些......
我尝试解决问题的第一步如下所示:
//build an info object and convert to json
NSDictionary *newDatasetInfo = [NSDictionary dictionaryWithObjectsAndKeys:name, @"name", language, @"language", nil];
//convert object to data
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:newDatasetInfo options:kNilOptions error:&error];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:someURLSetBefore];
[request setHTTPMethod:@"POST"];
// any other things to set in request? or working this way?
[[NSURLConnection alloc] initWithRequest:request delegate:self];
// What to do with NSURLConnection? Or how to send differently?
但我真的完全不知道如何使用 POST 方法将 JSON 对象发送到服务器。 有人可以帮我吗?
最佳答案
我通过尝试解决了这个问题,这是我的代码:
//build an info object and convert to json
NSDictionary *newDatasetInfo = [NSDictionary dictionaryWithObjectsAndKeys:name, @"name", language, @"language", nil];
//convert object to data
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:newDatasetInfo options:kNilOptions error:&error];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:someURLSetBefore];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPBody:jsonData];
// print json:
NSLog(@"JSON summary: %@", [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding]);
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
关于json - 如何在 iOS5 中将 JSON 数据对象发布到服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11434977/