zoukankan      html  css  js  c++  java
  • 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"]);//遍历数组
     
    }  
  • 相关阅读:
    1、常见ELK架构工作流程
    centos7系统zabbix 4.4版本升级到5.0版本
    K3s简介(一)
    三、saltstack数据系统grains
    爬取猫眼电影top100信息
    第一次爬虫实例
    docker容器轻量级web管理工具之portainer(六)
    liunx添加swap分区
    iptables 配置详解
    几个比较经典的算法问题的java实现
  • 原文地址:https://www.cnblogs.com/shenlaiyaoshi/p/9283980.html
Copyright © 2011-2022 走看看