• ios -本地存储和查看json数据


    1.代码创建json文件,并保存到本地
     
    第一步.设置json文件的保存路径
    NSString *filePath = [NSHomeDirectory() stringByAppendingString:@"/Documents/myJson.json"];
       
    NSLog(@"%@",filePath);
    第二步.准备存储数据

     

    NSMutableArray *arr = [[NSMutableArray alloc]init]; //用来盛放数据的value
       
    NSDictionary *dic = @{@"key1":@"value1",@"key2":@"value2",@"key3":@"value3",@"key4":@"value4"};
    NSDictionary *dic1 = @{@"key1":@"value1",@"key2":@"value2",@"key3":@"value3",@"key4":@"value4"};
    NSDictionary *dic2 = @{@"key1":@"value1",@"key2":@"value2",@"key3":@"value3",@"key4":@"value4"};
       
    [arr addObjectsFromArray:@[dic,dic1,dic2]];
       
       
    NSDictionary *json_dic = @{@"arr":arr};//key为arr value为arr数组的字典
    第三步.封包数据

     

    NSData *json_data = [NSJSONSerialization dataWithJSONObject:json_dic options:NSJSONWritingPrettyPrinted error:nil];
    第四步.写入数据

     

    [json_data writeToFile:filePath atomically:YES];
    经过这四步,就在本地指定路径filePath创建了一个json文件。(根目录是一个字典 key为arr value为arr数组的字典

     

    2.读取本地json数据

     

     
    NSString *filePath = [NSHomeDirectory() stringByAppendingString:@"/Documents/myJson.json"];//获取json文件保存的路径
       
    NSData *data = [NSData dataWithContentsOfFile:filePath];//获取指定路径的data文件
       
    id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; //获取到json文件的跟数据(字典)
     
    NSArray *arr = [json objectForKey:@"arr”];//获取指定key值的value,是一个数组
       
    for (NSDictionary *dic in arr) {
           
        NSLog(@"%@",[dic objectForKey:@"key1"]);//遍历数组
     
    }  
  • 相关阅读:
    mac下远程win8.1时提示"桌面连接无法验证您希望连接的计算机的身份"的解决办法
    在sublime text3下,用快捷键把文件打开到浏览器中
    实现多行文字对齐的原理
    js中===、==、!=、!===的区别
    sublime格式化HTML+CSS插件--HTML-CSS-JS Prettify
    实现多行文字居中方法(兼容IE6)
    telnet localhost 8089 ==》》命令使用
    在Tomcat下部属项目三种方式:
    java服务器
    可变参数
  • 原文地址:https://www.cnblogs.com/shenlaiyaoshi/p/9283980.html
Copyright © 2020-2023  润新知