简体   繁体   English

在快速将 JSON 数据转换为字符串时无法正确打印

[英]in swift converting JSON data to string doesn't print correctly

I am converting the (NS)Data to a string in Swift (2.2 atm) coming from a service call and I want to display it in the console.我正在将 (NS)Data 转换为来自服务调用的 Swift (2.2 atm) 字符串,我想在控制台中显示它。 so所以

let s = String(data: data!, encoding: NSUTF8StringEncoding)
print(s)

what I see has escaped character which is fairly useless to read我所看到的已转义字符,这是相当无用的阅读

Optional("{\"assets\":{\"err-fc2264112130e2c90bef0887b4367bb7\":{\"errors\": ...

is there a clever way to have it show the JSON without the \\" and missing the carriage returns. I thought of running the NSJSONSerialization twice (from data to foundation back to data with formatting on and then to string). I can do that but I wonder if there is some less irritating way.有没有一种聪明的方法可以让它显示没有 \\" 的 JSON 并缺少回车符。我想过两次运行 NSJSONSerialization(从数据到基础再到格式化数据然后到字符串)。我可以做到,但是我想知道是否有一些不那么刺激的方法。

You convert data to string, so the result you have is corrent, it's optional string. 您将数据转换为字符串,因此结果是正确的,它是可选的字符串。

If you want to get json result, you should just serialize the data. 如果要获取json结果,则只需序列化数据即可。

simply, 只是,

if let json = NSJSONSerialization.JSONObjectWithData(data!, 
    options: NSJSONReadingOptions.MutableContainers, error: nil) {
    print(json)
}

Try below solution:尝试以下解决方案:

let myStr = String(data: data!, encoding: .utf8)!
print(myStr as AnyObject)

There are more options, you can find in this answer: https://stackoverflow.com/a/68760531/3840884还有更多选项,您可以在此答案中找到: https : //stackoverflow.com/a/68760531/3840884

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM