我想將一個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)")
}
}
}
改變這一行'讓字典= value.convertToDictionary()' –