JSON Dictionary对象在Swift中的字符串

时间:2016-02-25 16:33:52

标签: json swift dictionary

我有一段时间试图将字典对象转换为我可以导出到.json文件的字符串。我试过了:

let data = try NSJSONSerialization.dataWithJSONObject(JSONDictionary, options: .PrettyPrinted)

立即失败:

  

***由于未捕获的异常终止应用程序' NSInvalidArgumentException',原因:' JSON写入的类型无效   (__NSDate)'

这是我的字典对象:

["latitude": 33.97300288084333, "longitude": -118.4644781426698, "parseID": qJd7QRojdU, "waves": (
        {
        avgSpeed = 0;
        course = 0;
        distance = "43.9934345945615";
        favorite = 0;
        maxSpeed = "5.420000076293945";
        time = "7.99999898672104";
        timestamp = "2016-02-05 16:05:21 +0000";
        wavelocation =         (
                        {
                altitude = 0;
                course = "78.046875";
                latitude = "33.9730028808433";
                longitude = "-118.46447814267";
                speed = "0.8199999928474426";
                timestamp = "2016-02-05 16:05:21 +0000";
            },
                        {
                altitude = 0;
                course = "71.3671875";
                latitude = "33.9730207342971";
                longitude = "-118.464455930626";
                speed = "1.080000042915344";
                timestamp = "2016-02-05 16:05:22 +0000";
            },
                        {
                altitude = 0;
                course = "69.2578125";
                latitude = "33.9730514958817";
                longitude = "-118.464368926472";
                speed = "1.080000042915344";
                timestamp = "2016-02-05 16:05:23 +0000";
            }

        );
    },
        {
        avgSpeed = 0;
        course = 0;
        distance = "112.301783225658";
        favorite = 0;
        maxSpeed = "4.670000076293945";
        time = "34.5915005803108";
        timestamp = "2016-02-05 16:36:56 +0000";
        wavelocation =         (
                        {
                altitude = 0;
                course = "-1";
                latitude = "33.9713087717363";
                longitude = "-118.463766921188";
                speed = "-1";
                timestamp = "2016-02-05 16:36:56 +0000";
            },
                        {
                altitude = 0;
                course = "58.8995221253856";
                latitude = "33.9713248007833";
                longitude = "-118.463470063933";
                speed = "3.448220014572144";
                timestamp = "2016-02-05 16:37:09 +0000";
            },
                        {
                altitude = 0;
                course = "61.875";
                latitude = "33.9713574294317";
                longitude = "-118.463396206608";
                speed = "3.710000038146973";
                timestamp = "2016-02-05 16:37:10 +0000";
            }

        );
    }
), "favorite": 0, "idleTime": 0, "paddleDistance": 2392.602, "distance": 0, "locationName": Venice Pier, "duration": 3730, "paddleTime": 412]

我在这上面摸不着头脑。我已经挖了一段时间(2天)寻找答案,但没有任何东西出现。任何帮助表示赞赏! - 罗布

2 个答案:

答案 0 :(得分:2)

处理易于与Web服务交换的日期的另一种方法是使用Unix时间戳 - 这是一个数字而不是字符串。

获取Unix时间戳:

let timestamp = date.timeIntervalSince1970

并将其转换回日期:

let date = NSDate(timeIntervalSince1970: timestamp)

答案 1 :(得分:1)

正如其他人所建议的那样,您可能需要将任何NSDate个对象转换为词典中的String个对象。

假设您需要在问题中详细说明的特定时间戳格式,则可以将NSDateFormatter与Unicode Date Formatting一起使用。

下面的一些粗略示例代码演示了如何实现此目的:

// get the current time as an example NSDate
let now = NSDate()

// format the date into the timestamp string using NSDateFormatter
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss xxxx"
let dateAsString = formatter.stringFromDate(now)

let dictToConvert = ["name": "Igor", "gender": "male", "time":dateAsString]

let savePath = NSHomeDirectory() + "/file.json"

do {
    let data = try NSJSONSerialization.dataWithJSONObject(dictToConvert, options: .PrettyPrinted)
    if data.writeToFile(savePath, atomically: true) {
        print("saved file in location: \(savePath))")
    } else {
        print("could not write file to location: \(savePath)")
    }
} catch {
    print("error: \(error)")
}