throb
throb

Reputation: 185

JSON Dictionary object to string in Swift

I am having a heck of a time trying to convert a dictionary object to a string I can export to a .json file. I have tried :

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

This fails immediately :

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (__NSDate)'

Here is my dictionary object :

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

I'm scratching my head on this. I have dug around SO for a while (2 days) looking for the answer but nothing is popping up. Any help is appreciated! - Rob

Upvotes: 0

Views: 297

Answers (2)

So Over It
So Over It

Reputation: 3698

As others have suggested, you may need to convert any NSDate objects to String objects in your dictionary.

Assuming that you need the specific timestamp format detailed in your question, you can use a NSDateFormatter with Unicode Date Formatting.

Some rough sample code below gives a demo of how to achieve this:

// 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)")
}

Upvotes: 1

Abizern
Abizern

Reputation: 150615

Another method of dealing with dates that is easy to exchange with a web service is to use the Unix Time Stamp - which is a number rather than a string.

To get the Unix Time Stamp:

let timestamp = date.timeIntervalSince1970

And to convert this back into a date:

let date = NSDate(timeIntervalSince1970: timestamp)

Upvotes: 2

Related Questions