2016-12-14 94 views
8

我試圖從Objc轉換到Swift,並有更好的日子。如何使用SwiftyJSON從文件保存/檢索字典

我有一個類的字典:

collaborationDictionary:[String:Set<String>] 

我想讀/寫此字典/從一個文件,只是不能完全似乎使其工作。我必須使用以下JSON結構來保存字典,並且必須使用SwiftyJSON。

{ "Collaborations" : { 
      "5604" : [ 
       "whiteboard.png", 
       "VID_20161123_135117.3gp", 
       "Photo_0.jpeg"] 
      "5603" : [ 
       "VID_20161123_135117.3gp"], 
      "5537" : [ 
       "Screenshot_20151212-132454.png", 
       "VID_20161202_083205.3gp", 
       "VID_20161123_135117.3gp", 
       "Photo_0.jpeg", 
       "Screenshot_20151212-132428.png", 
       "Screenshot_20151212-132520.png", 
       "IMG_20161017_5.jpg", 
       "whiteboard.png"]} 
} 

我沒有找到/檢索文件或寫入文件的任何實際問題。我只是不能完全弄清楚如何手動加載SwiftyJSON。我需要在頂部有一個名爲「Collaborations」的JSON對象。它需要包含協作ID字典(5604,5603 ...)。每個協作包含一個字符串(文件名)數組。我包括我用來讀/寫文件的代碼,但我需要SwiftyJSON庫的幫助。

這是我使用存儲上述數據的構件數據成員:

這些是我需要完成以下功能:

 private var collaborationDictionary:[String:Set<String>] = [:] 


    func getUploadedFileSet() { 
    collaborationDictionary = [:] 
    let documentsURL = URL(string: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]) 
    let appURL = documentsURL?.appendingPathComponent(APP_DISTINGUISHED_NAME) 
    let jsonFileURL = appURL?.appendingPathComponent(UPLOADED_ITEMS_DB_JSON) 

    if FileManager.default.fileExists(atPath: (jsonFileURL?.absoluteString)!) { 
     do { 
      let data = try Data(contentsOf: jsonFileURL!, options: .alwaysMapped) 
      let json = JSON(data: data) 

      // ************************************************ 
      // NEED HELP START 
      // NOW WHAT???? What is the SwiftyJSON code 

      ?????????????????????????     

      // NEED HELP END 
      // ************************************************ 

     } catch let error { 
      print(error.localizedDescription) 
     } 
    } 
} 

    func saveUploadedFilesSet() {   
    let documentsURL = URL(string: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]) 
    let appURL = documentsURL?.appendingPathComponent(APP_DISTINGUISHED_NAME) 
    let jsonFileURL = appURL?.appendingPathComponent(UPLOADED_ITEMS_DB_JSON) 

    do { 
     let dirExists = FileManager.default.fileExists(atPath: (appURL?.absoluteString)!) 
     if !dirExists { 
      try FileManager.default.createDirectory(atPath: (appURL?.absoluteString)!, withIntermediateDirectories: false, attributes: nil) 
     } 

     // ************************************************ 
     // NEED HELP START 
      // NOW WHAT???? What is the SwiftyJSON code 

      ?????????????????????????     

     // NEED HELP END 
     // ************************************************ 

     // Write to file code - haven't written it yet but that should be easy   

    } catch let error as NSError { 
     print(error.localizedDescription); 
    } 
} 

任何方向將不勝感激。謝謝!

編輯

我能弄清楚如何從文件加載附帶的JSON結構。這裏是代碼:

func getUploadedFileSet() { 
    let documentsURL = URL(string: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]) 
    let appURL = documentsURL?.appendingPathComponent(APP_DISTINGUISHED_NAME) 
    let jsonFileURL = appURL?.appendingPathComponent(UPLOADED_ITEMS_DB_JSON) 

    if FileManager.default.fileExists(atPath: (jsonFileURL?.absoluteString)!) { 
     do { 
      let data = try Data(contentsOf: jsonFileURL!, options: .alwaysMapped) 
      let json = JSON(data: data) 
      if json != nil { 
       for (key, subJson) in json[kCollaborations] { 
        let stringArray:[String] = subJson.arrayValue.map { $0.string! } 
        let stringSet = Set(stringArray) 
        collaborationDictionary.updateValue(stringSet, forKey: key) 
       } 
      } else { 
       print("Could not get json from file, make sure that file contains valid json.") 
      } 
     } catch let error { 
      print(error.localizedDescription) 
     } 
    } 

我還沒有想出如何將collaborationDictionary對象保存到文件。我最大的問題是弄清楚如何放入「協作」鍵。有任何想法嗎?

+0

你的具體問題是什麼? – Raphael

+0

具體來說,讀取和寫入json對象的代碼是什麼。我將重點介紹代碼需要驗證/修復或創建的部分。 – JustLearningAgain

+0

長話短說,你需要從磁盤加載文件?閱讀它作爲字符串?並使用SwiftyJSON序列化爲json? –

回答

5

我終於得到了這個工作。最大的問題是我無法將collaborationDictionary轉換爲JSON。我終於不得不把它轉換成數組字典或字典集。這裏有2種方法:

 // ************************************************************************** 
func getUploadedFileSet() { 
    let documentsURL = URL(string: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]) 
    let appURL = documentsURL?.appendingPathComponent(APP_DISTINGUISHED_NAME) 
    let jsonFileURL = appURL?.appendingPathComponent(UPLOADED_ITEMS_DB_JSON) 

    if FileManager.default.fileExists(atPath: (jsonFileURL?.absoluteString)!) { 
     do { 
      let data = try Data(contentsOf: jsonFileURL!, options: .alwaysMapped) 
      let json = JSON(data: data) 
      if json != nil { 
       for (key, subJson) in json[kCollaborations] { 
        let stringArray:[String] = subJson.arrayValue.map { $0.string! } 
        let stringSet = Set(stringArray) 
        collaborationDictionary.updateValue(stringSet, forKey: key) 
       } 
      } else { 
       print("Could not get json from file, make sure that file contains valid json.") 
      } 
     } catch let error { 
      print(error.localizedDescription) 
     } 
    } 
} 

// ************************************************************************** 
func saveUploadedFilesSet() { 
    let documentsURL = URL(string: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]) 
    let appURL = documentsURL?.appendingPathComponent(APP_DISTINGUISHED_NAME) 
    let jsonFileURL = appURL?.appendingPathComponent(UPLOADED_ITEMS_DB_JSON) 
    let adjustedJSONFileURL = URL(fileURLWithPath:(jsonFileURL?.absoluteString)!) 

    do { 
     let dirExists = FileManager.default.fileExists(atPath: (appURL?.absoluteString)!) 
     if !dirExists { 
      try FileManager.default.createDirectory(atPath: (appURL?.absoluteString)!, withIntermediateDirectories: false, attributes: nil) 
     } 

     // Convert set elements to arrays 
     var convertedCollaborationDictionary: [String:[String]] = [:] 
     for (sessionID, fileNameSet) in collaborationDictionary { 
      let array = Array(fileNameSet) 
      convertedCollaborationDictionary.updateValue(array, forKey: sessionID) 
     } 
     let json: JSON = JSON(convertedCollaborationDictionary) 
     let fullJSON: JSON = [kCollaborations:json.object] 
     let data = try fullJSON.rawData() 
     try data.write(to: adjustedJSONFileURL, options: .atomic) 

    } catch let error as NSError { 
     print(error.localizedDescription); 
    } 
} 
1

如果你深入到源,SwiftyJSON包裝JSONSerialization,它可以同時進行初始化和轉換回的數據是知道如何閱讀和自己從磁盤寫:

func readJSON() -> JSON? { 
     guard let url = Bundle.main.url(forResource: "data", withExtension: "json"), 
      let data = try? Data(contentsOf: url) else { 
      return nil 
     } 
     return JSON(data: data) 
    } 

    func write(json: JSON, to url: URL) throws { 
     let data = try json.rawData() 
     try data.write(to: url) 
    } 

注意,您可以加載包括你的Bundle在內的任何地方的靜態數據,但你只能寫入沙箱(即Documents目錄)。如果您打算讀取/寫入同一個文件,您可能希望從第一次運行時將Bundle複製到文檔目錄中。

你的示例JSON也不好(lint它)。 「Photo_0.jpeg」後需要逗號]

+0

我明白如何將JSON轉換爲數據對象並返回。如何加載在問題中指定的collaborationDictionary對象?如何將collaborationDictionary轉換回SwiftyJSON?JSON是正確的。數組元素後跟一個逗號,除非它們是數組中最後一個元素。 – JustLearningAgain

+0

您是否運行我發佈的代碼?如果將json複製到一個data.json文本文件並將該文件放入您的項目中,並調用它失敗的readJSON()函數(print(readJSON)顯示nil),但如果添加逗號,它將起作用,並在控制檯中獲得完整的JSON對象。 –

+0

問題是它沒有回答這個問題:問題是如何將以下成員數據:swiftyJSON(SJ)的collaborationDictionary:[String:Set ]和將其轉換回SJ。正如你從我的代碼中可以看到的,我已經將文件加載到數據對象中。我只是無法弄清楚如何將SwiftyJSON數據放入var collaborationDictionary:[String:Set ]。另外,我沒有把它寫入文件的實際代碼,但這也很簡單。我只是不知道如何將collaborationDictionary放入SwiftyJSON中。通過SwiftyJSON,我的意思是一個JSON對象。 – JustLearningAgain

相關問題