iOS json数据解析(2)

解析文件中的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下点击加号(+)将你要调取的文件加入进去就可以了

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值