- JSON(JavaScript Object Notation)是一種輕量級(jí)的數(shù)據(jù)交換格式,采用完全獨(dú)立于語(yǔ)言的文本格式,易于閱讀和編寫,同時(shí)也易于機(jī)器解析和生成
- JSON文件有兩種結(jié)構(gòu):
1 對(duì)象:"名稱/值"對(duì)的集合,以"{"開(kāi)始,以"}"結(jié)束,名稱和值中間用":"隔開(kāi)
2 數(shù)組:值的有序列表,以"["開(kāi)始,以"]"結(jié)束,中間是數(shù)據(jù),數(shù)據(jù)以","分隔
(JSON中的而數(shù)據(jù)類型:字符串汹押、數(shù)值BOOL睹晒、對(duì)象、數(shù)組)
例如:
{
"reason": "success",
"result": [
{
"movieId": "215977",
"movieName": "森林孤影",
"pic_url": "http://v.juhe.cn/movie/picurl?2583247"
},
{
"movieId": "215874",
"movieName": "從哪來(lái)渣蜗,到哪去",
"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進(jìn)行JSON解析
第一步:獲取JSON文件路徑
第二步:轉(zhuǎn)換為NSData類型
第三步:解析JSON數(shù)據(jù)
代碼如下:
<pre><code>
-
(void)jsonParser {
//step1:文件路徑
NSString *jsonPath = [[NSBundle mainBundle] pathForResource:@"MovieList" ofType:@"txt"];
//step2:轉(zhuǎn)換為NSData類型
NSData *jsonData = [NSData dataWithContentsOfFile:jsonPath];
//step3.解析json數(shù)據(jù)
NSError *error;
//第二個(gè)參數(shù):
//NSJSONReadingMutableContainers = (1UL << 0),解析完成返回的為可變的數(shù)組或者字典類型。
//NSJSONReadingMutableLeaves = (1UL << 1),解析完成返回的類型為NSMutableString陌宿,在iOS7及其以上不太好用。
//NSJSONReadingAllowFragments = (1UL << 2)允許json串最外層既不是數(shù)組也不是字典涧黄,但必須是有效的json片段,例如json串可以是一段字符串赋荆。
NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error];
if (resultDic) {//判斷解析是否得到正常數(shù)據(jù)
//判斷當(dāng)前對(duì)象是否支持json格式
if([NSJSONSerialization isValidJSONObject:resultDic]){
//將字典轉(zhuǎn)換為json串
NSData *strData = [NSJSONSerialization dataWithJSONObject:resultDic options:NSJSONWritingPrettyPrinted error:&error];
//判斷strData是否有值
if (strData) {
//將data轉(zhuǎn)換為字符串
NSString *str = [[NSString alloc] initWithData:strData encoding:NSUTF8StringEncoding];
NSLog(@"%@",str);
}
}
}
}