所以这是我从代码中获取post json数组的代码
// SENDING A POST JSON
NSString *post = [NSString stringWithFormat:@"plm=1"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://muvieplus.com/testjson/test.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];
NSURLResponse *requestResponse;
NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:nil];
NSString *requestReply = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding];
NSLog(@"%@", requestReply);
当我运行它时,我得到了requestReply
2014-11-07 14:22:15.565 JsonApp[1849:60b]
{
{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}
我如何解析这个json?有什么帮助吗?
答案 0 :(得分:2)
使用NSJSONSerialization
类从JSON数据中获取对象。
NSError *error;
NSDictionary *requestReply = [NSJSONSerialization JSONObjectWithData:[requestHandler bytes] options:NSJSONReadingAllowFragments error:&error]
if (requestReply) {
//use the dictionary
}
else {
NSLog("Error parsing JSON: %@", error);
}
这将返回一个字典(取决于数据,它可能是一个数组),其中包含JSON中的所有对象,然后您可以使用它来构建自己的对象或其他任何对象。
我建议调查异步请求的使用,可能使用NSURLSession
或第三方库,如AFNetworking
,因为这会使您的应用更具响应性。您甚至不应该使用同步API加载本地文件,更不用说发出网络请求,因为您的应用程序无法做任何其他事情(在当前线程上),直到获得响应为止可能需要很长时间,特别是当人们使用移动数据时。