Trying to figure out how to prettyPrint the json value of my response from an API, while debugging:
let session = URLSession(configuration: .default)
let task = session.dataTask(with: urlRequest) { data, response, error in
completion(data, response, error)
}
In the debugger, if I do po data, this is what I get something like this:
How can I print out the actual json structure that is in the data object? Was hoping to see something like this:
{ "firstName" : "John", "lastName" : "Doe", ... }
po debugPrint(data)
doesn't output anything in this case.
To receive JSON from a REST API endpoint, you must send an HTTP GET request to the REST API server and provide an Accept: application/json request header. The Accept header tells the REST API server that the API client expects JSON.
e print(String(data: JSONSerialization.data(withJSONObject: JSONSerialization.jsonObject(with: data, options: []), options: .prettyPrinted), encoding: .utf8)!)
Try the JSONSerialization
, something like this:
let url = URL(string: "http://date.jsontest.com")
var request : URLRequest = URLRequest(url: url!)
request.httpMethod = "GET"
let dataTask = URLSession.shared.dataTask(with: request) {
data,response,error in
do {
if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {
print(jsonResult)
}
} catch let error {
print(error.localizedDescription)
}
}
dataTask.resume()
Where jsonResult
will print out this:
{
date = "02-19-2018";
"milliseconds_since_epoch" = 1519078643223;
time = "10:17:23 PM";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With