解析文件中的json数据,将数据写到本地,通过json解析调取数据
首先创建一个.json文件或者拖拽一个.json文件到工程
创建.json文件,将数据写入 (Xcode有个Directions.geojson 文件,直接创建这个就好)
{
"weatherinfo":{"city":"北京","cityId":"101010100","temp1":"15","temp2":"5","weather":"多云","ptime":"08:00"}
}
然后在工程中调用:
-(void)simpleFileJson{
NSString *filePath =[[NSBundle mainBundle]pathForResource:@"Directions" ofType:@"geojson"];
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSLog(@"输出路径%@",filePath);
//是否存在这个路径下的文件
if ([fileMgr fileExistsAtPath:filePath]) {
NSString *jsonStr = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
id jsonObj = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
if ([jsonObj isKindOfClass:[NSDictionary class]]) {
NSDictionary *dic =(NSDictionary*)jsonObj;
NSDictionary *dic1 =[dic objectForKey:@"weatherinfo"];
NSLog(@"%@", [dic1 objectForKey:@"city"]);
}
if ([jsonObj isKindOfClass:[NSArray class]]) {
}
}else{
NSLog(@"没有找到文件");
}
}
其中注意: [[NSBundle mainBundle]pathForResource:@"Directions" ofType:@"geojson"]调用本地文件,但是运行会发现找不到文件,显示无法找到文件。我们需要在工程中进行一些修改才可以找到文件
在TARGETS->Build Phases -> Copy Bundle Resources下点击加号(+)将你要调取的文件加入进去就可以了