iOS --生产JSON格式,创建JSON文件,创建文件夹,指定储存

//生成json文件

- (void)onjson

{

//    如果数组或者字典中存储了  NSString, NSNumber, NSArray, NSDictionary, or NSNull 之外的其他对象,就不能直接保存成文件了.也不能序列化成 JSON 数据.

    NSDictionary *dict = @{@"name" : @"me", @"do" : @"something", @"with" : @"her", @"address" : @"home"};

    

    // 1.判断当前对象是否能够转换成JSON数据.

    // YES if obj can be converted to JSON data, otherwise NO

    BOOL isYes = [NSJSONSerialization isValidJSONObject:dict];

    

    if (isYes) {

        NSLog(@"可以转换");

        

        /* JSON data for obj, or nil if an internal error occurs. The resulting data is a encoded in UTF-8.

         */

        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];

        

        /*

         Writes the bytes in the receiver to the file specified by a given path.

         YES if the operation succeeds, otherwise NO

         */

        // 将JSON数据写成文件

        // 文件添加后缀名: 告诉别人当前文件的类型.

        // 注意: AFN是通过文件类型来确定数据类型的!如果不添加类型,有可能识别不了! 自己最好添加文件类型.

//        [jsonData writeToFile:@"/Users/xyios/Desktop/dict.json" atomically:YES];

        //存入NSDocumentDirectory

        NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;

        

        //创建文件夹

        NSString *patientPhotoFolder = [path stringByAppendingPathComponent:@"abdd"];

        NSFileManager *fileManager = [[NSFileManager alloc] init];

        [fileManager createDirectoryAtPath:patientPhotoFolder

               withIntermediateDirectories:NO

                                attributes:nil

                                     error:nil];

        //储存文件名称+格式

        NSString *savePath = [patientPhotoFolder stringByAppendingPathComponent:@"Desopdict.json"];

        NSLog(@"savePath is SY:%@",savePath);

        [jsonData writeToFile:savePath atomically:YES];

        

        NSLog(@"%@", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);

        

    } else {

        

        NSLog(@"JSON数据生成失败,请检查数据格式");

        

    }

    

}

转载于:https://www.cnblogs.com/shenlaiyaoshi/p/7954231.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值