Swift中字典與JSON轉(zhuǎn)換的方法
更新時(shí)間:2017年03月23日 10:36:12 作者:FlyElephant
Swift中經(jīng)常會(huì)遇到字典和字符串的相互轉(zhuǎn)換,本篇文章主要介紹了Swift中字典與JSON轉(zhuǎn)換的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。
Swift中經(jīng)常會(huì)遇到字典和字符串的相互轉(zhuǎn)換,因此可以轉(zhuǎn)換可以封裝起來,轉(zhuǎn)換代碼如下:
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 {
//如果設(shè)置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
}
實(shí)際測(cè)試:
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("字符串轉(zhuǎn)換之后的字典:\(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("字典轉(zhuǎn)換之后的字符串:\(convertResult)")
let array:[String] = ["FlyElephant","keso"]
print("數(shù)組轉(zhuǎn)換之后的數(shù)組:\(self.convertArrayToString(arr: array as [AnyObject]))")
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Swift設(shè)計(jì)思想Result<T>與Result<T,?E:?Error>類型解析
這篇文章主要為大家介紹了Swift設(shè)計(jì)思想Result<T>與Result<T,?E:?Error>的類型示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11
Swift?Error重構(gòu)的基礎(chǔ)示例詳解
這篇文章主要為大家介紹了Swift?Error基礎(chǔ)錯(cuò)誤處理的方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11
Swift之for循環(huán)的基礎(chǔ)使用學(xué)習(xí)
這篇文章主要為大家介紹了Swift之for循環(huán)的基礎(chǔ)學(xué)習(xí),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06
Swift 3.0基礎(chǔ)學(xué)習(xí)之下標(biāo)
這篇文章主要介紹了Swift 3.0基礎(chǔ)學(xué)習(xí)之下標(biāo)的相關(guān)資料,文中介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用swift具有一定的參考價(jià)值,需要的朋友下面來一起看看吧。2017-03-03

