将JSON转换为Dictionary Swift时出错

问题描述 投票:0回答:1

你能帮助我吗?如果JSON带有这样的多线,我就会面临一个问题

"{\"groupId\":\"58\",\"chat\":\"send 2lines\nsecondline\"}"

我正在从服务器获取响应并使用此功能进行转换

    let dataDic = self.convertToDictionary(text: (remoteMessage.appData["message"]! as AnyObject) as! String)
    print(dataDic!)

这是我的功能

func convertToDictionary(text: String) -> [String: AnyObject]? {
    if let data = text.data(using: String.Encoding.utf8) {
        do {
            let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:AnyObject]
            return json

        } catch {
            print(error.localizedDescription)
        }
    }
    return nil
}

但问题出现了,如果代码有多行,因为它在返回时放了\ n它给了我

The data couldn’t be read because it isn’t in the correct format 

Error Domain=NSCocoaErrorDomain Code=3840 "Unescaped control character around character 145." UserInfo={NSDebugDescription=Unescaped control character around character 145.}
swift
1个回答
0
投票

在解析JSON之前,您应该在“\ n”之前添加一个额外的“\”。尝试使用“replacementOccurencesOf”功能。这样,您的JSON在解析之前就被格式化了。

© www.soinside.com 2019 - 2024. All rights reserved.