为了账号安全,请及时绑定邮箱和手机立即绑定

在SWIFT中将字典转换为JSON

在SWIFT中将字典转换为JSON

慕容708150 2019-07-27 15:15:07
在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呢?
查看完整描述

3 回答

?
米脂

TA贡献1836条经验 获得超3个赞

SWIFT 3.0

使用SWIFT 3,名称为NSJSONSerialization和它的方法已经改变了,根据SWIFT API设计指南.

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



查看完整回答
反对 回复 2019-07-28
?
慕神8447489

TA贡献1780条经验 获得超1个赞

我对你的问题的回答如下

let dict = ["0": "ArrayObjectOne", "1": "ArrayObjecttwo", "2": "ArrayObjectThree"]var error : NSError?let jsonData = try! NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions.PrettyPrinted)let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)! as Stringprint(jsonString)

答案是

{
  "0" : "ArrayObjectOne",
  "1" : "ArrayObjecttwo",
  "2" : "ArrayObjectThree"}


查看完整回答
反对 回复 2019-07-28
  • 3 回答
  • 0 关注
  • 252 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号