服务器之家

服务器之家 > 正文

Swift中字典与JSON转换的方法

时间:2021-01-05 14:41     来源/作者:FlyElephant

Swift中经常会遇到字典和字符串的相互转换,因此可以转换可以封装起来,转换代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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
}

实际测试:

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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]))")

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

原文链接:http://www.jianshu.com/p/210254495d57

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享 2020-04-07
电视剧《琉璃》全集在线观看 琉璃美人煞1-59集免费观看地址
电视剧《琉璃》全集在线观看 琉璃美人煞1-59集免费观看地址 2020-08-12
返回顶部