Swift中字典與JSON轉換的方法
更新時間:2017年03月23日 10:36:12 作者:FlyElephant
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]))")
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Swift使用SnapKit模仿Kingfisher第三方擴展優(yōu)化
這篇文章主要為大家介紹了Swift?SnapKit模仿Kingfisher第三方擴展優(yōu)化示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-09-09

