swift3.0 字典 <-互转-> 字符串
swift3.0 字典 <-互转-> 字符串
赵大财 发表于1年前
swift3.0 字典 <-互转-> 字符串
  • 发表于 1年前
  • 阅读 90
  • 收藏 0
  • 点赞 0
  • 评论 0

腾讯云 技术升级10大核心产品年终让利>>>   

贡献者:赵大财
博客: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, options: [])
            let str = String(data:data, encoding: String.Encoding.utf8)!
            return str
        } catch  {
            return ""
        }
    }
    
}

 

共有 人打赏支持
粉丝 21
博文 148
码字总数 33278
×
赵大财
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: