NSString *path = [[NSBundle mainBundle]pathForResource:@"mytest2" ofType:@"json"];
//获取文件路径后,从文件中读取数据:
NSData *jsonData = [[NSFileManager defaultManager] contentsAtPath:path];
//获取文件数据后,解析Json文件, It converts it into a dictionary.
CJSONDeserializer *jsonDeserializer = [CJSONDeserializer deserializer];
NSError *error = nil;
NSDictionary *jsonDict = [jsonDeserializer deserializeAsDictionary:jsonData error:&error];
if (error) {
//handle Error, didn't have here.
NSLog(@"JSON 解析错误!");
}
// //此时jsonDict保存的就是解析后的Json数据了。
// NSString *text = [jsonDict valueForKey:@"text"];
// NSLog(@"text = %@",text);
//
// //数字
// NSNumber *d01 = [jsonDict valueForKey:@"digi"];
// NSAssert(d01, @"Didn't have a key named digi");
// NSLog(@"digi = %3.1f", [d01 floatValue]);
//读取的时候还是先读取出一个NSDictionary对象,但是我们随后从中取出数组:
NSArray *dictArray = [jsonDict valueForKey:@"主界面"];
//此时获取到NSDictionary的对象就与原来的字典对象很像了,直接通过valueForKey取对应的配置使用即可
for (NSDictionary *dict in dictArray) {
NSString *text = [dict valueForKey:@"text"];
NSLog(@"dic_text = %@",text);
NSString *dir = [dict valueForKey:@"dir"];
NSLog(@"dic_dir = %@",dir);
NSString *icon = [dict valueForKey:@"icon"];
NSLog(@"dic_icon = %@",icon);
}
NSArray *dictArray2 = [jsonDict valueForKey:@"网站界面"];
for (NSDictionary *dict2 in dictArray2) {
NSString *text = [dict2 valueForKey:@"text"];
NSLog(@"dic2_text = %@",text);
NSString *url = [dict2 valueForKey:@"url"];
NSLog(@"dic2_url = %@",url);
NSString *icon = [dict2 valueForKey:@"icon"];
NSLog(@"dic2_icon = %@",icon);
}
NSArray *dictArray3 = [jsonDict valueForKey:@"图表界面"];
for (NSDictionary *dict3 in dictArray3) {
NSString *text = [dict3 valueForKey:@"text"];
NSLog(@"dic3_text = %@",text);
NSNumber *d03 = [dict3 valueForKey:@"digi"];
NSAssert(d03, @"Didn't have a key named digi");
NSLog(@"dic3_digi = %3.1f", [d03 floatValue]);
NSString *icon = [dict3 valueForKey:@"icon"];
NSLog(@"dic3_icon = %@",icon);
}
NSArray *dictArray4 = [jsonDict valueForKey:@"mytest"];
for (int i = 0; i < [dictArray4 count]; i++) {
NSLog(@"%@\n", [dictArray4 objectAtIndex:i]);
}
json 文件
{
"主界面" :
[
{
"text" : "网站" ,
"dir" : "web" ,
"icon" : "m1.png"
} ,
{
"text" : "图表" ,
"dir" : "graph" ,
"icon" : "m2.png"
} ,
{
"text" : "视频" ,
"dir" : "video" ,
"icon" : "m3.png"
} ,
{
"text" : "照片" ,
"dir" : "pic" ,
"icon" : "m4.png"
}
],
"网站界面" :
[
{
"text" : "网站1" ,
"url" : "http://www.123.com" ,
"icon" : "m1.png"
} ,
{
"text" : "网站2" ,
"url" : "http://www.456.com" ,
"icon" : "m2.png"
}
],
"图表界面" :
[
{
"text" : "2010-10销售额" ,
"digi" : 48.6 ,
"icon" : "m1.png"
} ,
{
"text" : "2010-11销售额" ,
"digi" : 75.3 ,
"icon" : "m2.png"
} ,
{
"text" : "2010-12销售额" ,
"digi" : 62.5 ,
"icon" : "m3.png"
}
],
"mytest" : [19,34,56]
}