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/39154907/

相关文章:

java - 我如何定义一个javabean来使用Jackson反序列化json?

java - Flexjson - 如何序列化包括 Map 的复杂层次结构

python - 解析一行中的多个json对象

swift - Firebase 类型 "ViewController"的值没有成员 'ref'

c# - Switch-Case 数据包处理的替代方案

swift - 枚举变量的模式翻转

cocoa - Swift 中 Array<Prototocol> 中对象的索引

c# - 从 JsonConverter 运行默认序列化逻辑

jquery - 按字母顺序对 JSON 进行排序

json - 使用ajax获取json数据时出现500错误