【发布时间】:2018-03-02 04:27:49
【问题描述】:
我想知道是否有任何方法可以在记录时以漂亮的格式打印准确的 JSON 字符串。我正在打印一个 http 请求标头字段,例如,
let jsonData = try JSONSerialization.data(withJSONObject: dictionary, options: .prettyPrinted)
let jsonString = String(bytes: jsonData, encoding: String.Encoding.utf8)
MyLogUtil.logVerbose(message: "\(String(describing: jsonString))")
但不是像下面那样打印预期的日志,
{
"user": {
name: "Test",
age: "30"
}
}
它的打印类似于,
{\n"user": {\nname: "Test",\n\nage: "30"\n}\n}\n
如何解决这个问题?
编辑: @AwaisFayyaz
func requestTest() -> Void {
let task = URLSession.shared.dataTask(with: URL(string: "https://jsonplaceholder.typicode.com/posts")!) { (data, response, error) in
do {
let json = try JSONSerialization.jsonObject(with: data!, options: []) as! [String: Any]
if let userDict = json["user"] as? NSDictionary {
print(userDict)
}
}
catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
}
task.resume()
}
上面的代码崩溃了!
【问题讨论】:
-
kkkk jsonString 它已经是一个可选的
String?。您需要做的就是打开您的选项。if let jsonString = ...。即使 Xcode 建议您应该使用,您也可能永远不需要使用String(describing:)方法。顺便说一句,使用字符串插值来显示字符串是没有意义的。只需在打开包装后打印您的 jsonString 即可。print(jsonString)或在你的情况下MyLogUtil.logVerbose(message: jsonString) -
你试过
.sortedKeys而不是.prettyPrinted吗?看起来prettyPrinted中的空白可能会导致问题。 -
@Jake 没用
-
@LeoDabus 感谢您的建议,但是格式错误呢,它仍然会在日志中打印 '\n\n' 内容
标签: ios json swift parsing logging