发布于 2017-05-24 22:57:31 | 220 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的精品教程,程序狗速度看过来!

JSON 数据交换格式

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。易于人阅读和编写,同时也易于机器解析和生成。它基于JavaScript(Standard ECMA-262 3rd Edition - December 1999)的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。这些特性使JSON成为理想的数据交换语言。


Swift中经常会遇到字典和字符串的相互转换,本篇文章主要介绍了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]))")

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持PHPERZ。



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务