iOS 读取和写 本地json文件

这俩天写毕设,在网上抓取数据搞不到,只能改笨办法使用本地文件了,

一下是一些基础的方法,记下来。

读本地文件

  NSError*error;
    //获取文件路径
    NSString *filePath = [[NSBundlemainBundle]pathForResource:filename ofType:@"json"];
  
    //根据文件路径读取数据
    NSData *jdata = [[NSDataalloc]initWithContentsOfFile:filePath];
   
    //格式化成json数据    
  id jsonObject = [NSJSONSerializationJSONObjectWithData:jdataoptions:kNilOptionserror:&error];

  

将Json存进本地文件夹
  NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path=[paths objectAtIndex:0];
    NSString *Json_path=[path stringByAppendingPathComponent:@"JsonFile.json"];
    //==写入文件
    NSLog(@"%@",[JsonData writeToFile:Json_path atomically:YES] ? @"Succeed":@"Failed");-----------------------
  //读取Json//==Json文件路径
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path=[paths objectAtIndex:0];
    NSString *Json_path=[path stringByAppendingPathComponent:@"JsonFile.json"];
    //==Json数据
    NSData *data=[NSData dataWithContentsOfFile:Json_path];
    //==JsonObject
    id JsonObject=[NSJSONSerialization JSONObjectWithData:data
                                                   options:NSJSONReadingAllowFragments
                                                     error:&error]  //nslog (@"%@",jsonobject);打印json字

  

 

posted @ 2016-04-28 11:55  HObOCat  阅读(1860)  评论(0)    收藏  举报