Creating json in swift

Create your object, in this case a Dictionary:

let dic = ["test1":0, "test2":1435659978, "test3":1430479596]

Create the JSON data from the object:

do {
    let dic = ["test1":0, "test2":1435659978, "test3":1430479596]
    let jsonData = try NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted)
} catch let error as NSError {
    print(error)
}

Use the JSON data as a String if you need it:

do {
    let dic = ["test1":0, "test2":1435659978, "test3":1430479596]
    let jsonData = try NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted)
    let str = String(data: jsonData, encoding: NSUTF8StringEncoding)
} catch let error as NSError {
    print(error)
}

Leave a Comment