XcodeparsingJson

所以这是我的代码从一个url获得一个后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"} ]} 

我怎样才能parsing这个JSON? 请帮忙吗?

使用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中所有对象的字典(取决于数据,它可能是一个数组),然后可以使用它来构build自己的对象或任何其他对象。

我会build议调查使用asynchronous请求,可能使用NSURLSession或像AFNetworking第三方库,因为这将使您的应用程序更具响应性。 你甚至不应该使用同步API加载一个本地文件,更不用说做一个networking请求了,因为你的应用程序将无法做任何事情(在当前线程上),直到它得到一个响应,这可能是一个非常很长时间,特别是当人们使用手机数据的时候。