是否有“漂亮打印” JSON字符串更好的办法比我使用

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

我有JSON数据来自服务器端。

如果我用下面的代码我得到不漂亮印一行字符串:

print(String(bytes: jsonData, encoding: String.Encoding.utf8))

为了让漂亮的印刷我用下面的代码:

if let json = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) {
   if let prettyPrintedData = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) {
      print(String(bytes: prettyPrintedData, encoding: String.Encoding.utf8) ?? "NIL")
   }
}

但目前看来,这是不是最好的方法。

因此,没有任何人知道如何漂亮打印接收jsonData打印呢?

json swift pretty-print
2个回答
1
投票

你有什么稍微漂亮的版本:

if let json = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers), let jsonData = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) {
    print(String(decoding: jsonData, as: UTF8.self))
} else {
    print("json data malformed")
}

-1
投票

我想不到的东西比原生型漂亮。

if let json = try? JSONSerialization.jsonObject(with: jsonData, options: []) {
    if let jsonArray = json as? [Any] { print(jsonArray) }
    else if let jsonDict = json as? [String:Any] { print(jsonDict) }
    else { print("Couldn't convert json") }
}
© www.soinside.com 2019 - 2024. All rights reserved.