標籤:
- JSON(JavaScript Object Notation)是一種輕量級的資料交換格式,採用完全獨立於語言的文字格式設定,易於閱讀和編寫,同時也易於機器解析和產生
- JSON檔案有兩種結構:
1 對象:”名稱/值”對的集合,以”{“開始,以”}”結束,名稱和值中間用”:”隔開
2 數組:值的有序列表,以”[“開始,以”]”結束,中間是資料,資料以”,”分隔
(JSON中的而資料類型:字串、數值BOOL、對象、數組)
例如:
{"reason": "success","result": [ { "movieId": "215977", "movieName": "森林孤影", "pic_url": "http://v.juhe.cn/movie/picurl?2583247" }, { "movieId": "215874", "movieName": "從哪來,到哪去", "pic_url": "http://v.juhe.cn/movie/picurl?2583542" }, { "movieId": "215823", "movieName": "有一天", "pic_url": "http://v.juhe.cn/movie/picurl?2583092" }],"error_code": 0 }
進行JSON解析步驟
- 擷取JSON檔案路徑
- 轉換為NSData類型
- 解析JSON資料
代碼如下:
- (void)jsonParser { //step1:檔案路徑 NSString *jsonPath = [[NSBundle mainBundle] pathForResource:@"MovieList" ofType:@"txt"]; //step2:轉換為NSData類型 NSData *jsonData = [NSData dataWithContentsOfFile:jsonPath]; //step3.解析json資料 NSError *error; //第二個參數: //NSJSONReadingMutableContainers = (1UL << 0),解析完成返回的為可變的數組或者字典類型。 //NSJSONReadingMutableLeaves = (1UL << 1),解析完成返回的類型為NSMutableString,在iOS7及其以上不太好用。 //NSJSONReadingAllowFragments = (1UL << 2)允許json串最外層既不是數組也不是字典,但必須是有效json片段,例如json串可以是一段字串。 NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error]; if (resultDic) {//判斷解析是否得到正常資料 //判斷當前對象是否支援json格式 if([NSJSONSerialization isValidJSONObject:resultDic]){ //將字典轉換為json串 NSData *strData = [NSJSONSerialization dataWithJSONObject:resultDic options:NSJSONWritingPrettyPrinted error:&error]; //判斷strData是否有值 if (strData) { //將data轉換為字串 NSString *str = [[NSString alloc] initWithData:strData encoding:NSUTF8StringEncoding]; NSLog(@"%@",str); } } }}
iOS資料解析之JSON解析