現在很多服務器返回的數據格式都是JSON格式的數據。 JSON數據傳輸格式全稱javaScript Object Notation是基于Javascript的輕量級的數據交換格式 
JSON中數據類型 對應 OC中數據類型
數字(整數或浮點數) NSNumber字符串(在雙引號中) " "邏輯值(true 或 false) NSNumber數組(在方括號中) NSArray對象(字典 在花括號中) NSDictionarynull [NSNull null] 注意在判斷值是否為空時使用此種方式注意一下代碼中我的JSON數據是從文件中獲取的,一般來說我們都是從服務器中獲取的JSON數據,LLJsonModel是根據返回的數據自定義的一個Model類。
// JSON解析 // 從文件中得到JSON數據 NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"json"]; // 讀取json數據 NSData *jsonData = [NSData dataWithContentsOfFile:filePath]; // 查看得到的數據 NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; NSLog(@"jsonStr==%@", jsonStr); // NSJSONSerialization 解析 NSError *error = nil; NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error]; if (!error) { NSLog(@"dic====%@", dic); // 取錯誤信息 判斷一下 NSLog(@"error_msg==%@", dic[@"error_msg"]); NSArray *modelArr = dic[@"people"]; for (NSDictionary *dic in modelArr) { LLJsonModel *album = [LLJsonModel new]; [album setValuesForKeysWithDictionary:dic]; [self.jsonArray addObject:album]; } NSLog(@"jsonArray===%@", self.jsonArray); // 展示到UI上 } else { NSLog(@"error:%@", error); }在線校驗json格式 http://json.parser.online.fr http://www.json.cn
新聞熱點
疑難解答