gpt4 book ai didi

json - 使用 Swift 将 JSON 转换为数据时遇到问题

转载 作者:行者123 更新时间:2023-11-30 13:05:44 25 4
gpt4 key购买 nike

我正在尝试学习 Swift。我的一个项目是尝试从内部 Web 服务(一组 Python CGI 脚本)检索 JSON 数据并将其转换为 Swift 对象。我可以在 Python 中轻松做到这一点,但在 Swift 中却遇到了困难。这是我的 Playground 代码:

import UIKit

import XCPlayground

XCPlaygroundPage.currentPage.needsIndefiniteExecution = true

let endpoint: String = "http://pathToCgiScript/cgiScript.py"
let url = NSURL(string: endpoint)
let urlrequest = NSMutableURLRequest(URL: url!)
let headers: NSDictionary = ["User-Agent": "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)",
"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"]
urlrequest.allHTTPHeaderFields = headers as? [String : String]
urlrequest.HTTPMethod = "POST"

let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let task = session.dataTaskWithRequest(urlrequest) {
(data, response, error) in
guard data != nil else {
print("Error: did not receive data")
return
}
guard error == nil else {
print("Error calling script!")
print(error)
return
}
do {
guard let received = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as?
[String: AnyObject] else {
print("Could not get JSON from stream")
return
}
print(received)

} catch {
print("error parsing response from POST")
}
}
task.resume()

我知道通过“POST”来检索数据可能看起来很奇怪,但这就是系统的设置方式。我不断得到:

Could not get data from JSON

我检查了响应,状态为 200。然后我检查了数据的描述:

print(data?.description)

我得到了意想不到的结果。这是一个片段:

Optional("<0d0a5b7b 22535441 54555322 3a202244 6f6e6522 2c202242 55535922...

我使用了Mirror,显然类型是NSData。不知道该怎么做。我尝试使用 base64EncodedDataWithOptions 对数据进行编码。我也尝试过不同的 NSJSONReadingOptions 但无济于事。有什么想法吗?

更新:

我使用 Wireshark 仔细检查了 Playground 中的代码。不仅调用正确,而且发回的数据也正确。事实上,Wireshark 将数据视为 JSON。问题在于尝试将 JSON 数据转换为 Swift 对象。

最佳答案

我知道出了什么问题了。我转换为错误的类型。这是新代码:

guard let received = try! NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments) as? [AnyObject] 

JSON 没有返回字典数组,而是返回对象数组。

关于json - 使用 Swift 将 JSON 转换为数据时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39402249/

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