亲宝软件园·资讯

展开

swift 字典 json Swift中字典与JSON转换的方法

FlyElephant 人气:3
想了解Swift中字典与JSON转换的方法的相关内容吗,FlyElephant在本文为您仔细讲解swift 字典 json的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:swift,字典,json,swift3.0,字典转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]))")

加载全部内容

相关教程
猜你喜欢
用户评论