現(xiàn)在很多服務(wù)器返回的數(shù)據(jù)格式都是JSON格式的數(shù)據(jù)。 JSON數(shù)據(jù)傳輸格式全稱javaScript Object Notation是基于Javascript的輕量級的數(shù)據(jù)交換格式 
JSON中數(shù)據(jù)類型 對應(yīng) OC中數(shù)據(jù)類型
數(shù)字(整數(shù)或浮點數(shù)) NSNumber字符串(在雙引號中) " "邏輯值(true 或 false) NSNumber數(shù)組(在方括號中) NSArray對象(字典 在花括號中) NSDictionarynull [NSNull null] 注意在判斷值是否為空時使用此種方式注意一下代碼中我的JSON數(shù)據(jù)是從文件中獲取的,一般來說我們都是從服務(wù)器中獲取的JSON數(shù)據(jù),LLJsonModel是根據(jù)返回的數(shù)據(jù)自定義的一個Model類。
// JSON解析 // 從文件中得到JSON數(shù)據(jù) NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"json"]; // 讀取json數(shù)據(jù) NSData *jsonData = [NSData dataWithContentsOfFile:filePath]; // 查看得到的數(shù)據(jù) 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
新聞熱點
疑難解答
圖片精選