以纯 Swift 3 种方式将 swift 对象(带有嵌套对象)转换为 JSON 数据

Convert swift object (with nested objects) to JSON data in a pure Swift 3 way

我正在尝试将 swift 对象转换为 JSON,我已经看到这些 SO 问题 & ,但我无法将其应用到我的代码中。

我有一个 swift 类型的 [String : DailyTimes] 对象,我想以纯 Swift 3 方式将它转换回 JSON 数据,没有任何库.

下面是我的习惯class:

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 数据(来自 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" ]
                 ]
                 ]
     ]

我尝试将 [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)")
                    }



                }

            }

此方法:

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

要求 dictionary 为 "property list"。还有一个:

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

不是 属性 列表。

为什么?因为 self.times[Times] 类型,它不是 属性 列表类型。您需要在此处调用 self.times.map{[=16=].convertToDictionary()) 以便将 times 转换为 属性 列表。

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

试试这个:

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([=10=].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)")
    }
}