我已经使用“ wordsapi”写了一个网络请求,并且状态为200,但是收到的响应不在json中。
我的代码可以构建并运行,我只需要json中的响应即可。
let wordsAPI =
"https://wordsapiv1.p.mashape.com/words/money/synonyms"
let wordsAPIEndPoint = NSURL(string: wordsAPI)
let request = NSMutableURLRequest(url: wordsAPIEndPoint! as
URL)
request.setValue("mapkey", forHTTPHeaderField: "X-Mashape-Key")
request.httpMethod = "GET"
let session = URLSession.shared
let synonymResponse = session.dataTask(with: request as
URLRequest) { (data, response, error) -> Void in
if let resp = response as? HTTPURLResponse {
print(resp)
}
}
synonymResponse.resume()
//我收到的回复
{ Status Code: 200, Headers {
"Accept-Ranges" = (
bytes
);
"CF-RAY" = (
"4d4d9aacabdccf5c-IAD"
);
Connection = (
"keep-alive"
);
"Content-Length" = (
30
);
"Content-Type" = (
"application/json; charset=utf-8"
);Date = (
"Fri, 10 May 2019 17:24:00 GMT"
);
我需要在json中获取我设置为端点的任何值的同义词的响应。在这种情况下是“钱”
答案 0 :(得分:2)
您需要完整使用data
var,其中包含收到的json数据
let wordsAPI = "https://wordsapiv1.p.mashape.com/words/money/synonyms"
let wordsAPIEndPoint = URL(string: wordsAPI)
var request = URLRequest(url: wordsAPIEndPoint!)
request.setValue("mapkey", forHTTPHeaderField: "X-Mashape-Key")
request.httpMethod = "GET"
URLSession.shared.dataTask(with: request) { (data, response, error) -> Void in
guard let data = data else { return }
let res = try! JSONDecoder().decode(Root.self,from:data)
print(res.synonyms)
}.resume()
struct Root:Codable {
let word:String
let synonyms:[String]
}