I have json data comes server side.
In case I use the next code I get not pretty printed one line string:
print(String(bytes: jsonData, encoding: String.Encoding.utf8))
To make it pretty printed I use the next code:
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")
}
}
But seems that it isn't the best way.
So does anybody know how to pretty print incoming jsonData to print it?
jsonData
come from originally? At the place you need it pretty printed, do you have the source object it was generated from? – Bambara.mutableContainers
is pointless in Swift and really pointless just for the sake of pretty printing. – Christian..., options: [])
. And since that is the default, simply leave off theoptions:
parameter. – Christiandump
the deserialized object. Also, I'd recommend usingCodable
instead ofJSONSerialization
– Bambara