iOS開發(fā)中獲取JSON數(shù)據(jù)是一個常見的需求,JSON是一種和XML類似的數(shù)據(jù)交換格式,其簡潔、易讀、易解析的特點廣受開發(fā)者歡迎。在iOS中,我們可以通過NSURLConnection或NSURLSession來獲取JSON數(shù)據(jù)。
下面的代碼演示了如何使用NSURLConnection來獲取JSON數(shù)據(jù):
NSURL *url = [NSURL URLWithString:@"https://example.com/api/data.json"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; [connection start];
在NSURLConnection的delegate方法中,我們可以解析JSON數(shù)據(jù):
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { self.data = [NSMutableData new]; } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [self.data appendData:data]; } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { NSError *error; NSDictionary *json = [NSJSONSerialization JSONObjectWithData:self.data options:kNilOptions error:&error]; if (!error) { // 解析JSON成功 } else { // 解析JSON失敗 } }
對于NSURLSession,我們可以使用completionHandler來獲取JSON數(shù)據(jù):
NSURLSession *session = [NSURLSession sharedSession]; NSURL *url = [NSURL URLWithString:@"https://example.com/api/data.json"]; NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { if (!error) { NSError *jsonError; NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError]; if (!jsonError) { // 解析JSON成功 } else { // 解析JSON失敗 } } else { // 獲取JSON數(shù)據(jù)失敗 } }]; [task resume];
無論是NSURLConnection還是NSURLSession,獲取JSON數(shù)據(jù)的核心是通過NSJSONSerialization來解析JSON數(shù)據(jù)。如果JSON數(shù)據(jù)格式不正確,則解析會失敗。