字典转data后去掉空格和转义字符

通常字典转data我们会使用JSONSerialization的类方法,但转化后的字典转为字符串JSON串后会带有空格以及转义字符。

解决办法:将转义字符以及空格用空字符串替换掉,代码如下

let modeString = "dark"
        let themeDict = ["theme": modeString]
        if let data = try? JSONSerialization.data(withJSONObject: themeDict, options: .prettyPrinted), var utf8 = String.init(data: data, encoding: .utf8) {
            utf8 = utf8.replacingOccurrences(of: "\n", with: "").replacingOccurrences(of: " ", with: "")
            if let themeJsonString = utf8.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
             
            }
        }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。