贡献者:赵大财
博客:https://my.oschina.net/zhaodacai
GitHub:https://github.com/zhaodacai
字典 转成 字符串: 下面有写好的扩展你可以直接使用
var dictionary = [[String:Any]]() let dict1 = ["age":"22","ddd":"gg"] let dict2 = ["age":"33","w":""] dictionary.append(dict1) dictionary.append(dict2) let data = try? JSONSerialization.data(withJSONObject: dictionary,options: []) let str = String(data:data!,encoding: String.Encoding.utf8)! print(str )
字符串 转成 字典:
let json:String = (CHUser.shareInstance.userInfo?.tag_data)! //json = json.replacingOccurrences(of: "/",with: "") //加上这句直接打印可中文 guard let jsonData = json.data(using: .utf8) else { return } do { let dict = try JSONSerialization.jsonObject(with: jsonData,options:JSONSerialization.ReadingOptions.mutableContainers) print(dict) } catch { print("失败") }
2016年11月29日 封装了一下
extension String { var md5: String! { let str = self.cString(using: String.Encoding.utf8) let strLen = CC_LONG(self.lengthOfBytes(using: String.Encoding.utf8)) let digestLen = Int(CC_MD5_DIGEST_LENGTH) let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen) CC_MD5(str!,strLen,result) let hash = NSMutableString() for i in 0..<digestLen { hash.appendFormat("%02x",result[i]) } result.deallocate(capacity: digestLen) return String(format: hash as String) } var toAny:Any! { guard let jsonData = self.data(using: .utf8) else { return nil } do { let any = try JSONSerialization.jsonObject(with: jsonData,options:JSONSerialization.ReadingOptions.mutableContainers) return any } catch { return nil } } } //////////////////////////////////////////////////// extension NSArray { var toString:String! { do { let data = try JSONSerialization.data(withJSONObject: self,options: []) let str = String(data:data,encoding: String.Encoding.utf8)! return str } catch { return "" } } } //////////////////////////////////////////////////// extension NSDictionary { var toString:String! { do { let data = try JSONSerialization.data(withJSONObject: self,encoding: String.Encoding.utf8)! return str } catch { return "" } } }原文链接:/swift/322696.html