程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 更多關於編程 >> Swift中字典與JSON轉換的方法

Swift中字典與JSON轉換的方法

編輯:更多關於編程

Swift中字典與JSON轉換的方法。本站提示廣大學習愛好者:(Swift中字典與JSON轉換的方法)文章只能為提供參考,不一定能成為您想要的結果。以下是Swift中字典與JSON轉換的方法正文


Swift中經常會遇到字典和字符串的相互轉換,因此可以轉換可以封裝起來,轉換代碼如下:

func convertStringToDictionary(text: String) -> [String:AnyObject]? {
  if let data = text.data(using: String.Encoding.utf8) {
    do {
      return try JSONSerialization.jsonObject(with: data, options: [JSONSerialization.ReadingOptions.init(rawValue: 0)]) as? [String:AnyObject]
    } catch let error as NSError {
      print(error)
    }
  }
  return nil
}


func convertDictionaryToString(dict:[String:AnyObject]) -> String {
  var result:String = ""
  do {
    //如果設置options為JSONSerialization.WritingOptions.prettyPrinted,則打印格式更好閱讀
    let jsonData = try JSONSerialization.data(withJSONObject: dict, options: JSONSerialization.WritingOptions.init(rawValue: 0))

    if let JSONString = String(data: jsonData, encoding: String.Encoding.utf8) {
      result = JSONString
    }

  } catch {
    result = ""
  }
  return result
}

func convertArrayToString(arr:[AnyObject]) -> String {
  var result:String = ""
  do {
    let jsonData = try JSONSerialization.data(withJSONObject: arr, options: JSONSerialization.WritingOptions.init(rawValue: 0))

    if let JSONString = String(data: jsonData, encoding: String.Encoding.utf8) {
      result = JSONString
    }

  } catch {
    result = ""
  }
  return result
}

實際測試:

 

  let jsonText:String = "{\"order_info\":[{\"order_id\":\"1479828084819597144\",\"channel\":\"ios\",\"product_id\":\"02\"},{\"order_id\":\"1479828084819597144\",\"channel\":\"ios\",\"product_id\":\"02\"}]}"

  let dict = self.convertStringToDictionary(text: jsonText)
  print("字符串轉換之後的字典:\(dict!)")


  var dictionaryOrArray : [String: AnyObject] = [:]
  dictionaryOrArray["a\"b"] = "cd" as AnyObject?
  dictionaryOrArray["strings"] = ["string", "another"] as AnyObject?
  dictionaryOrArray["keywdict"] = [ "anotherKey": 100, "Key2": "Val2"] as AnyObject?
  dictionaryOrArray["numbers"] = [ 1, 2, 3] as AnyObject?
  dictionaryOrArray["bools"] = [ true, false] as AnyObject?
  let convertResult:String = self.convertDictionaryToString(dict: dictionaryOrArray)
  print("字典轉換之後的字符串:\(convertResult)")


  let array:[String] = ["FlyElephant","keso"]
  print("數組轉換之後的數組:\(self.convertArrayToString(arr: array as [AnyObject]))")

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved