2017-08-27 37 views
2

我想將一個swift對象轉換爲JSON,我已經看到這些問題1 & 2,但我無法將它應用於我的代碼。將swift對象(帶嵌套對象)轉換爲純Swift 3方式中的JSON數據

我有一個類型爲[String : DailyTimes]的swift對象,我想以純Swift 3方式將其轉換回JSON數據,不需要任何庫。

下面是我的自定義類:

class AvailabilityTimes:{ 

    struct Times{ 
     var startTime : String? 
     var endTime : String? 


    } 

    struct DailyTimes{ 
     let weekday : String 
     var available : Bool 
     var times = [Times]() 
     mutating func update(times: [Times]){ 
      self.times = times 
     } 

    } 
} 

轉換後的JSON數據(從斯威夫特對象)會是這個樣子:

[ 
    "Monday": [ "weekday" : "Monday", 
       "available" : true, 
       "times": [ 
        ["startTime": "9:00 AM", "endTime": "1:30 PM" ], 
        ["startTime": "2:30 PM", "endTime": "6:00 PM" ], 
        ["startTime": "7:30 PM", "endTime": "9:00 PM" ] 
       ] 
    ], 
    "Tuesday": [ "weekday" : "Tuesday", 
       "available" : true, 
       "times": [ 
        ["startTime": "9:00 AM", "endTime": "6:00 PM" ] 
       ] 
       ] 
    ] 

我不成功的嘗試[String : DailyTimes]轉換成JSON數據

第1步:在兩個結構中都添加了convertToDictionary函數。

class AvailabilityTimes:{ 

    struct Times{ 
     var startTime : String? 
     var endTime : String? 

     func convertToDictionary() -> Dictionary<String, Any> { 
      return [ 
       "startTime" : self.startTime, 
       "endTime" : self.endTime 
      ] 
     } 
    } 

    struct DailyTimes{ 
     let weekday : String 
     var available : Bool 
     var times = [Times]() 
     mutating func update(times: [Times]){ 
      self.times = times 
     } 

     func convertToDictionary() -> Dictionary<String, Any> { 
      return [ 
       "weekday" : self.weekday, 
       "available" : self.available, 
       "times"  : self.times 
      ] 
     } 

    } 
} 

這是我嘗試轉換爲JSON數據失敗的地方。

步驟2:該功能可轉換爲JSON數據

func convertTimesObjectToJSON(timesObject: [String : DailyTimes]){ 

       for (key, value) in timesObject{ 

        let dictionary = value.convertToDictionary 

        print("dictionary", dictionary) 
        do{ 
         let theJSONData = try JSONSerialization.data(withJSONObject: dictionary, options: .prettyPrinted) 
        } catch let error{ 
         print("error: \(error)") 
        } 



       } 

      } 
+0

改變這一行'讓字典= value.convertToDictionary()' –

回答

3

此方法:

JSONSerialization.data(withJSONObject: dictionary, options: .prettyPrinted) 

要求dictionary是一個 「屬性列表」。和一個這樣的:

 [ 
      "weekday" : self.weekday, 
      "available" : self.available, 
      "times"  : self.times 
     ] 

不是屬性列表。

爲什麼?因爲self.times的類型是[Times],它不是屬性列表類型。您需要在此撥打self.times.map{$0.convertToDictionary()),以便將times轉換爲屬性列表。

func convertToDictionary() -> Dictionary<String, Any> { 
    return [ 
     "weekday" : self.weekday, 
     "available" : self.available, 
     "times"  : self.times.map{$0.convertToDictionary()) 
    ] 
} 
2

試試這個:

struct DailyTimes{ 
    let weekday : String 
    var available : Bool 
    var times = [Times]() 
    mutating func update(times: [Times]){ 
     self.times = times 
    } 

    func convertTimesToDictionary() -> [Any] { 
     var timeDict:[Any] = [] 
     self.times.forEach({ timeDict.append($0.convertToDictionary())}) 
     return timeDict 
    } 

    func convertToDictionary() -> Dictionary<String, Any> { 
     return [ 
      "weekday" : self.weekday, 
      "available" : self.available, 
      "times"  : self.convertTimesToDictionary() 
     ] 
    } 
} 

功能轉換成JSON:

func convertToJSONObject(timesObject: [String : DailyTimes]) -> [String:AnyObject] { 
    var dailyTimesObject:[String:AnyObject] = [:] 
    for (key, value) in timesObject { 
     dailyTimesObject.updateValue(value.convertToDictionary() as AnyObject, forKey: key) 
    } 
    return dailyTimesObject 
} 

func convertTimesObjectToJSON(timesObject: [String : DailyTimes]){ 
    do{ 
     let theJSONData = try JSONSerialization.data(withJSONObject: convertToJSONObject(timesObject: timesObject), options: .prettyPrinted) 
     print(String(data: theJSONData, encoding: String.Encoding.utf8)!) 
    } catch let error{ 
     print("error: \(error)") 
    } 
}