gpt4 book ai didi

swift - 将 JSON 转换为 Dictionary Swift 时出错

转载 作者:行者123 更新时间:2023-11-30 11:44:05 25 4
gpt4 key购买 nike

你能帮我吗, 如果 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.}

最佳答案

在解析 JSON 之前,您应该在“\n”之前添加一个额外的“\”。尝试使用“replacingOccurencesOf”函数。这样你的 JSON 就会在解析之前被格式化。

关于swift - 将 JSON 转换为 Dictionary Swift 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49042703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com