Swift 解析 Google 搜索 API 文本文件
Swift Parse Google Search API Text File
我正在尝试解析 Google 在 http://suggestqueries.google.com/complete/search?client=firefox&q=YOURQUERY 的搜索自动完成端点的结果,但它返回的是一个没有键的文本文件。
这是一个示例输出:
["YOURQUERY",["yourquery","yourquery dou","yourquery s.r.o","yourquery отзывы","yourquery львів","yourquery s.r.o. львів"]]
这是我的代码:
let baseURL = "http://suggestqueries.google.com/complete/search?client=firefox&q="
var searchResults: [String] = []
func returnResults(searchTerm: String, completion: @escaping ([String?], Error?) -> Void) {
let finalUrl = URL(string: baseURL + searchTerm)
// 3. choose method to transmit and configure to do so
var request = URLRequest(url: finalUrl!)
request.httpMethod = "GET"
// 4. request data
URLSession.shared.dataTask(with: request) { (data, _, error) in
// check for errors and data
if let error = error {
print("There was an error requesting data")
return completion([], error)
}
guard let data = data else {
print("There was an error getting data.", error)
return completion([], NSError())
}
// if we got our data back, we need to decode it to match our model object
let jsonDecoder = JSONDecoder()
do {
// 1. decode results into array
let results = try jsonDecoder.decode([String].self, from: data)
// 2. set search results var equal to our decoded results array
self.searchResults = results
completion(results, nil)
} catch {
print("There was an error decoding data.", error)
completion([], error)
}}.resume()
}
我收到解码错误:
There was an error decoding data. typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 1", intValue: 1)], debugDescription: "Expected to decode String but found an array instead.", underlyingError: nil))
你会如何正确解码?
你的问题是返回的 JSON 是一个 Any
的数组。第一个元素是 String
,第二个是字符串数组 [String]
。由于 Any
不符合 Decodable
因此使用 JSONSerialization
方法会更容易
class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any
将结果从 Any
转换为 [Any]
并将最后一个元素转换为字符串数组 [String]
.
let results = try (JSONSerialization.jsonObject(with: data) as? [Any])?.last as? [String] ?? []
print(results)
这将打印
"["yourquery", "yourquery dou", "yourquery s.r.o", "yourquery отзывы",
"yourquery львів", "yourquery s.r.o. львів"]\n"
我正在尝试解析 Google 在 http://suggestqueries.google.com/complete/search?client=firefox&q=YOURQUERY 的搜索自动完成端点的结果,但它返回的是一个没有键的文本文件。
这是一个示例输出:
["YOURQUERY",["yourquery","yourquery dou","yourquery s.r.o","yourquery отзывы","yourquery львів","yourquery s.r.o. львів"]]
这是我的代码:
let baseURL = "http://suggestqueries.google.com/complete/search?client=firefox&q="
var searchResults: [String] = []
func returnResults(searchTerm: String, completion: @escaping ([String?], Error?) -> Void) {
let finalUrl = URL(string: baseURL + searchTerm)
// 3. choose method to transmit and configure to do so
var request = URLRequest(url: finalUrl!)
request.httpMethod = "GET"
// 4. request data
URLSession.shared.dataTask(with: request) { (data, _, error) in
// check for errors and data
if let error = error {
print("There was an error requesting data")
return completion([], error)
}
guard let data = data else {
print("There was an error getting data.", error)
return completion([], NSError())
}
// if we got our data back, we need to decode it to match our model object
let jsonDecoder = JSONDecoder()
do {
// 1. decode results into array
let results = try jsonDecoder.decode([String].self, from: data)
// 2. set search results var equal to our decoded results array
self.searchResults = results
completion(results, nil)
} catch {
print("There was an error decoding data.", error)
completion([], error)
}}.resume()
}
我收到解码错误:
There was an error decoding data. typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 1", intValue: 1)], debugDescription: "Expected to decode String but found an array instead.", underlyingError: nil))
你会如何正确解码?
你的问题是返回的 JSON 是一个 Any
的数组。第一个元素是 String
,第二个是字符串数组 [String]
。由于 Any
不符合 Decodable
因此使用 JSONSerialization
方法会更容易
class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any
将结果从 Any
转换为 [Any]
并将最后一个元素转换为字符串数组 [String]
.
let results = try (JSONSerialization.jsonObject(with: data) as? [Any])?.last as? [String] ?? []
print(results)
这将打印
"["yourquery", "yourquery dou", "yourquery s.r.o", "yourquery отзывы", "yourquery львів", "yourquery s.r.o. львів"]\n"