我需要将JSON对象从Algolia映射到一个Model。
这是我的ViewModel:
import Foundation
import AlgoliaSearchClient
class AlgoliaViewModel: ObservableObject {
@Published var idList: [MySearchModel] = []
func search(text: String, index: String) {
let client = SearchClient(appID: "XXX", apiKey: "XXX")
let index = client.index(withName: IndexName(rawValue: index))
let query = Query(text)
index.search(query: query) { result in
if case .success(let response) = result {
print("Response: \(response)")
do {
let hits: Array = response.hits
DispatchQueue.main.async {
self.idList = hits.map({
MySearchModel(searchValue: $0.objectID.rawValue)
})
print(self.idList)
}
}
catch {
print("JSONSerialization error:", error)
}
}
}
}
}目前,我只有一个objectID为searchValue的模型。
如何访问对象的所有其他属性并将其映射到模型?
发布于 2020-10-28 01:41:52
import Foundation
import AlgoliaSearchClient
class AlgoliaViewModel: ObservableObject {
@Published var list: [MySearchModel] = []
func search(text: String, index: String) {
let client = SearchClient(appID: "XXX", apiKey: "XXX")
let index = client.index(withName: IndexName(rawValue: index))
let query = Query(text)
index.search(query: query) { result in
if case .success(let response) = result {
print("Response: \(response)")
do {
let hits: Array = response.hits
DispatchQueue.main.async {
self.list = hits.map({MySearchModel.init})
print(self.list)
}
}
catch {
print("JSONSerialization error:", error)
}
}
}
}
}https://stackoverflow.com/questions/63732602
复制相似问题