您的位置:首页 > 移动开发 > IOS开发

iOS数据解析之JSON解析

2016-05-06 21:36 417 查看
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);
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: