gpt4 book ai didi

ios - 将 NSData 转换为可读的 JSON 格式 Swift

转载 作者:行者123 更新时间:2023-11-28 21:20:02 29 4
gpt4 key购买 nike

我正在从 Google Calendar Free/Busy API 提取数据。我在对 POST 的响应中获得的 JSON 数据被编码为 NSData,转换为字符串但我看不到完整的响应。我在将 NSData 转换为可以查看来自 Google 的完整响应的格式时遇到问题。

这是来自 Google 的预期响应:

{
"kind": "calendar#freeBusy",
"timeMin": "2016-10-17T17:40:00.000Z",
"timeMax": "2016-10-17T17:45:00.000Z",
"calendars": {
"ID_REDACTED@resource.calendar.google.com": {
"busy": [
{
"start": "2016-10-17T17:40:00Z",
"end": "2016-10-17T17:45:00Z"
}
]
}
}
}

但我只能在响应中看到这么多数据:

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

我不知道如何在“日历:”之后公开 JSON 响应的最后一部分

这是我的代码:

func fetchEvents() {
for (calID,_) in dict {
let request = NSMutableURLRequest(URL: NSURL(string: "https://www.googleapis.com/calendar/v3/freeBusy?access_token=\(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 {
print(myJSONError)
}

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

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!)")
}
task.resume()
}
}

我试过 NSJSONSerialization.dataWithJSONdata 但没有成功。我认为这是因为 NSData 在这里被转换成一个字符串:

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

它不显示完整的 JSON 响应。我觉得数据需要转换为 [String:AnyObject],但我不是 100% 确定。

感谢您的帮助!

最佳答案

let responseString = String(data: data!, encoding: NSUTF8StringEncoding) 不对响应应用任何魔法,它只是将服务器发送的字节转换为字符。如果您没有看到您希望看到的内容,那是因为服务器没有发送它。

关于ios - 将 NSData 转换为可读的 JSON 格式 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40095297/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com