加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在Swift中将字典转换为JSON

发布时间:2020-12-14 06:08:20 所属栏目:百科 来源:网络整理
导读:我创建了下一个词典: 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,NSJSONS
我创建了下一个词典:
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
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读