2017-08-27 5 views
2

Je suis en train de convertir un objet swift en JSON, j'ai vu ces questions SO 1 & 2, mais je ne pouvais pas l'appliquer à mon code .Convertir objet swift (avec des objets imbriqués) en données JSON dans un pur Swift 3 way

J'ai un objet rapide de type [String : DailyTimes] que je voudrais convertir en données JSON d'une manière pure Swift 3, sans bibliothèques.

est Ci-dessous ma classe personnalisée:

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 
     } 

    } 
} 

Les données JSON converties (de l'objet Swift) ressemblerait à quelque chose comme ceci:

[ 
    "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" ] 
       ] 
       ] 
    ] 

Ma tentative infructueuse de convertir [String : DailyTimes] aux données JSON

Étape 1: Ajout de la fonction convertToDictionary dans les deux structures.

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 
      ] 
     } 

    } 
} 

C'est où j'essaye sans succès de convertir en données JSON.

Étape 2: Fonction qui convertit les données 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

changez cette ligne 'laisser le dictionnaire = value.convertToDictionary()' –

Répondre

3

Cette méthode:

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

exige que dictionary d'être une "liste de biens". Et un ceci:

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

Ce n'est pas une liste de propriétés.

Pourquoi? Parce que self.times est de type [Times], ce qui n'est pas un type de liste de propriétés. Vous devez appeler self.times.map{$0.convertToDictionary()) ici afin de convertir times à une liste de propriétés.

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

Essayez ceci:

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() 
     ] 
    } 
} 

Fonction convertir en 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)") 
    } 
}