首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS 將 JSON 對象轉換為 Plist 文件存儲的完整實現

     編輯:程式設計綜合問答

需求場景

將包含巢狀數組與對象的複雜 JSON 數據持久化為 Plist 文件,便於本地讀取與備份。

核心實現代碼

- (void)writeJSONToPlist:(NSString *)jsonString {
    // 1. JSON 字符串 -> NSData
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    // 2. NSData -> NSDictionary (頂層對象)
    NSError *error = nil;
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData 
                                                         options:NSJSONReadingMutableContainers 
                                                           error:&error];
    if (error) {
        NSLog(@"JSON 解析失敗: %@", error.localizedDescription);
        return;
    }
    
    // 3. 獲取 Document 目錄路徑
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docPath = [paths firstObject];
    NSString *plistPath = [docPath stringByAppendingPathComponent:@"user-data.plist"];
    
    // 4. 寫入 Plist (自動處理巢狀結構)
    BOOL success = [dict writeToFile:plistPath atomically:YES];
    if (success) {
        NSLog(@"Plist 寫入成功: %@", plistPath);
    } else {
        NSLog(@"Plist 寫入失敗");
    }
}

關鍵技術細節

  • NSJSONReadingMutableContainers:生成可變容器,便於後續修改
  • writeToFile:atomically::原子寫入防止數據損壞,自動處理 NSArray/NSDictionary 序列化
  • Plist 格式天然支援:NSString, NSNumber, NSDate, NSData, NSArray, NSDictionary

驗證與調試

// 讀取驗證
NSDictionary *loaded = [NSDictionary dictionaryWithContentsOfFile:plistPath];
NSLog(@"載入數據: %@", loaded);

// 查看文件物理位置 (模擬器)
NSLog(@"文件路徑: %@", plistPath); // 輸出路徑可在 Finder 中打開

進階擴展

  1. 大數據量時改用 NSOutputStream 分塊寫入
  2. 添加版本號字段支持數據遷移
  3. 敏感數據寫入前加密(CommonCrypto / RNCryptor)
  4. 考慮使用 SQLite (FMDB/CoreData) 替代 Plist 以支持查詢與事務
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved