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

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

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

https://stackoverflow.com/questions/29625133/

相关文章:

javascript - 在 JavaScript 中将 JSON 字符串解析为特定的对象原型(pr

ios - 如何使用 NSJSONSerialization

python - 为什么我看到 "TypeError: string indices must be

python - 将类实例序列化为 JSON

python - 存储 Python 字典

java - HttpServletRequest 获取 JSON POST 数据

jquery - 为什么每个人都为 jQuery 选择 JSON 而不是 XML?

c# - 如何将 C# 匿名类型序列化为 JSON 字符串?

php - json_encode() 转义正斜杠

javascript - JSON 省略了 Infinity 和 NaN; ECMAScript 中