通常字典转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) {
}
}
网友评论