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

2019-07-19  本文已影响0人  大一号

通常字典转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) {
             
            }
        }
上一篇下一篇

猜你喜欢

热点阅读