iOS 数据转json工具

2019-07-30  本文已影响0人  Cingjin
//生成json文件

- (void)yxj_json:(NSDictionary *)jsonDic fileName:(NSString *)fileName {
    
    //    如果数组或者字典中存储了  NSString, NSNumber, NSArray, NSDictionary, or NSNull 之外的其他对象,就不能直接保存成文件了.也不能序列化成 JSON 数据.
    
    // 1.判断当前对象是否能够转换成JSON数据.
    
    // YES if obj can be converted to JSON data, otherwise NO
    
    BOOL isYes = [NSJSONSerialization isValidJSONObject:jsonDic];
    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:jsonDic 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:@"Test"];
        
        NSFileManager *fileManager = [[NSFileManager alloc] init];
        
        [fileManager createDirectoryAtPath:patientPhotoFolder withIntermediateDirectories:NO attributes:nil error:nil];
        //储存文件名称+格式
        NSString *savePath = [patientPhotoFolder stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.json",fileName]];
        NSLog(@"savePath is SY:%@",savePath);
        [jsonData writeToFile:savePath atomically:YES];
        NSLog(@"%@", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
    } else {
        NSLog(@"JSON数据生成失败,请检查数据格式");
    }
}

// 读取本地JSON文件
- (NSDictionary *)yxj_readLocalFileWithName:(NSString *)name {
    // 获取文件路径
    NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"json"];
    // 将文件数据化
    NSData *data = [[NSData alloc] initWithContentsOfFile:path];
    // 对数据进行JSON格式化并返回字典形式
    return [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
}


上一篇下一篇

猜你喜欢

热点阅读