- 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
}
使用Foundation進行JSON解析
第一步:獲取JSON文件路徑
第二步:轉換為NSData類型
第三步:解析JSON數據
代碼如下:
<pre><code>
-
(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);
}
}
}
}