use*_*776 3 ios nsjsonserialization swift3
我正在尝试将 swift 对象转换为 JSON,我已经看到了这些 SO question 1 & 2,但我无法将其应用于我的代码。
我有一个 swift 类型的对象[String : DailyTimes],我想以纯 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
}
}
}
Run Code Online (Sandbox Code Playgroud)
转换后的 JSON 数据(来自 Swift 对象)看起来像这样:
[
"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" ]
]
]
]
Run Code Online (Sandbox Code Playgroud)
我尝试转换[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
]
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我尝试转换为 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)")
}
}
}
Run Code Online (Sandbox Code Playgroud)
这种方法:
JSONSerialization.data(withJSONObject: dictionary, options: .prettyPrinted)
Run Code Online (Sandbox Code Playgroud)
要求它dictionary是一个“属性列表”。还有这个:
[
"weekday" : self.weekday,
"available" : self.available,
"times" : self.times
]
Run Code Online (Sandbox Code Playgroud)
不是属性列表。
为什么?因为self.timesis 属于 type [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())
]
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1412 次 |
| 最近记录: |