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數據生成失敗,請檢查數據格式");

        

    }

    

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM