一尘不染

快速创建JSON

swift

我想快速创建一个像这样的json:

{
    "test1": 0,
    "test2": 1435659978,
    "test3": 1430479596
}

如何创建此json?


阅读 578

收藏
2020-07-07

共1个答案

一尘不染

创建您的对象,在这种情况下为字典:

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

从对象创建JSON数据:

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

如果需要,请使用JSON数据作为字符串:

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)
}
2020-07-07