快速创建json [英] Creating json in swift

查看:17
本文介绍了快速创建json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to createa json like this in swift:

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

我如何创建这个 json?

How can I create this json?

推荐答案

创建您的对象,在本例中为字典:

Create your object, in this case a Dictionary:

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

从对象创建 JSON 数据:

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

如果需要,将 JSON 数据用作字符串:

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

这篇关于快速创建json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆