json - 在 Swift 中将字典转换为 JSON

标签 json swift serialization

我已经创建了下一个字典:

var postJSON = [ids[0]:answersArray[0], ids[1]:answersArray[1], ids[2]:answersArray[2]] as Dictionary

我得到:

[2: B, 1: A, 3: C]

那么,如何将其转换为 JSON?

最佳答案

Swift 3.0

根据 Swift API Design Guidelines,在 Swift 3 中,NSJSONSerialization 的名称及其方法发生了变化。 .

let dic = ["2": "B", "1": "A", "3": "C"]

do {
    let jsonData = try JSONSerialization.data(withJSONObject: dic, options: .prettyPrinted)
    // here "jsonData" is the dictionary encoded in JSON data

    let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
    // here "decoded" is of type `Any`, decoded from JSON data

    // you can now cast it with the right type        
    if let dictFromJSON = decoded as? [String:String] {
        // use dictFromJSON
    }
} catch {
    print(error.localizedDescription)
}

Swift 2.x

do {
    let jsonData = try NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted)
    // here "jsonData" is the dictionary encoded in JSON data

    let decoded = try NSJSONSerialization.JSONObjectWithData(jsonData, options: [])
    // here "decoded" is of type `AnyObject`, decoded from JSON data

    // you can now cast it with the right type 
    if let dictFromJSON = decoded as? [String:String] {
        // use dictFromJSON
    }
} catch let error as NSError {
    print(error)
}

swift 1

var error: NSError?
if let jsonData = NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted, error: &error) {
    if error != nil {
        println(error)
    } else {
        // here "jsonData" is the dictionary encoded in JSON data
    }
}

if let decoded = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as? [String:String] {
    if error != nil {
        println(error)
    } else {
        // here "decoded" is the dictionary decoded from JSON data
    }
}

关于json - 在 Swift 中将字典转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29625133/

相关文章:

javascript - 如何从 json 获取对未命名数组的引用

javascript - Angular 在 Controller 中使用 Json 数据

ios - 如何将阴影添加到 UIButton 边框而不是文本

java - 在这种情况下,与添加 serialVersionUID 相比,抑制警告不是更好的选择吗?

javascript - 过滤电影列表 JavaScript

具有指定标签的 PHP Json 值

ios - Swift 4 - SceneKit 上的 SpriteKit - 防止触摸底层相机控件

python - 在 Python 中,如何将 YAML 映射加载为 OrderedDicts?

.net - 我可以在不注释类的情况下自定义Json.NET序列化吗?