美文网首页
JSON数据转换

JSON数据转换

作者: 微凉初夏 | 来源:发表于2019-10-08 16:16 被阅读0次

    字典:

    extension Dictionary {
    
    /// 将字典转为 JSON 字符串
    ///
    /// - Returns: JSON 字符串
    func toJSONData() -> Data? {
        guard JSONSerialization.isValidJSONObject(self) else {return nil}
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
            return jsonData
        }catch {
            return nil
        }
    }
    }
    

    数组:

    extension Array {
    
    /// 将数组转为 JSON 字符串
    ///
    /// - Returns: JSON 字符串
    func toJSONData() -> Data? {
        guard JSONSerialization.isValidJSONObject(self) else {return nil}
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
            return jsonData
        }catch {
            return nil
        }
    }
    }
    

    字符串

    extension String {
    func toJSONData() -> Data? {
        return self.data(using: .utf8)
    }
    }
    

    Data数据

    extension Data {
    
    func JSONToStr() -> String {
        return String(data: self, encoding: .utf8) ?? ""
    }
    
    /// JSON 解析
    ///
    /// - Returns: JSON 解析后的对象
    func JSONToAny() -> Any {
        do {
            let result = try JSONSerialization.jsonObject(with: self, options: .mutableContainers)
            return result
        } catch  {
            return self
        }
    }
    
    /// 图片压缩
    func compressImage(maxKB: CGFloat? = 1024.0) -> UIImage? {
        let size = CGFloat(self.count) / 1024.0 / maxKB!
        var rate: CGFloat = 1.0 - 0.1 * size
        if rate < 0.1 { rate = 0.1 }
        
        return UIImage(data: self, scale: rate)
    }
    
    }

    相关文章

      网友评论

          本文标题:JSON数据转换

          本文链接:https://www.haomeiwen.com/subject/jqsoectx.html