user3282173 user3282173 - 9 days ago 4
JSON Question

Converting NSData to readable JSON format Swift

I am pulling data from Google Calendar Free/Busy API. The JSON data that I get in the response to the POST is encoded as NSData, converted to a String but I cannot see the full response. I am having trouble converting the NSData to a format where I can see the entire response from Google.

This is the expected response from Google:

"kind": "calendar#freeBusy",
"timeMin": "2016-10-17T17:40:00.000Z",
"timeMax": "2016-10-17T17:45:00.000Z",
"calendars": {
"": {
"busy": [
"start": "2016-10-17T17:40:00Z",
"end": "2016-10-17T17:45:00Z"

But I can only see this much data in the response:

responseString = {
"kind": "calendar#freeBusy",
"timeMin": "2016-10-17T17:40:00.000Z",
"timeMax": "2016-10-17T17:45:00.000Z"

I cannot figure out how to expose the last part of the JSON response after 'calendars:'

Here is my code:

func fetchEvents() {
for (calID,_) in dict {
let request = NSMutableURLRequest(URL: NSURL(string: "\(GIDSignIn.sharedInstance().currentUser.authentication.accessToken)")!)
request.HTTPMethod = "POST"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")

let jsonObject: [String:AnyObject] = [
"timeMin" : "2016-10-17T10:40:00-07:00",
"timeMax" : "2016-10-17T10:45:00-07:00",
"items" : [
"id" : "\(calID)"


do {
let data1 = try NSJSONSerialization.dataWithJSONObject(jsonObject, options: NSJSONWritingOptions.PrettyPrinted)
let convertedString = String(data: data1, encoding: NSUTF8StringEncoding)
json = convertedString!

} catch let myJSONError {

request.HTTPBody = json.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else {

if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response!)")

let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString!)")

I have tried NSJSONSerialization.dataWithJSONdata with no luck. I think that because the NSData is being converted into a String here:

let responseString = String(data: data!, encoding: NSUTF8StringEncoding)

it does not show the full JSON response. I feel like the data needs to be cast as [String:AnyObject] but I'm not 100% sure.

Thanks for the help!


let responseString = String(data: data!, encoding: NSUTF8StringEncoding) does not apply any magic on the response, it just converts the bytes sent by the server to characters. If you don't see something you'd expect to see, that's because the server doesn't send it.