亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在SWIFT中將字典轉換為JSON

在SWIFT中將字典轉換為JSON

慕婉清6462132 2019-12-18 13:12:38
在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 回答

?
慕的地6264312

TA貢獻1817條經驗 獲得超6個贊

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-12-19
?
慕工程0101907

TA貢獻1887條經驗 獲得超5個贊

我對你的問題的回答如下

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-12-19
  • 3 回答
  • 0 關注
  • 510 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號