[英]How to access a json response in SwiftUI?
所以我发出一个 HTTP 请求,我得到一个如下所示的响应:
{
"code": 200,
"status": "success",
"patients": {
"bogdanp": {
"_id": "5e77c7bbc7cbd30024f3eadb",
"name": "Bogdan Patient",
"phone": "0732958473"
},
"robertp": {
"_id": "5e77c982a2736a0024e895fa",
"name": "Robert Patient",
"phone": "0739284756"
}
}
}
如何将“bogdanp”作为字符串获取,以及如何访问对象属性? 例如,如何访问“姓名”或“电话”等?
这是我的 HTTP 代码:
func getPatients(link: String, username: String)
{
var code = 0 // this is the variable that stores the error code from the response, it is initially set to 0
let parameters: [String : Any] = ["username": username]
let url = URL(string: link)!
let session = URLSession.shared
var request = URLRequest(url: url)
request.httpMethod = "POST"
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
} catch _ {
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
do {
if let jsonResponse = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
// Here I want to access the json response
}
} catch _ {
}
})
task.resume()
}
使用 SwiftUI 发出调用请求的最佳方法是使用 Combine。
您首先必须创建要取回的 JSON 对象的模型:
import Foundation
//MARK: - Your object to retrieve from JSON
struct Doctor: Codable, Identifiable {
let id = UUID()
let patients: [Patients]
}
struct Patients: Codable {
let id: String
let name: String
let phone: String
}
然后,您创建一个类,该类将使用 Combine 处理您的 JSON 请求(我为您添加了一个加号来处理任何响应错误):
import Foundation
import Combine
class Network {
// Handle your request errors
enum Error: LocalizedError {
case invalidResponse
case addressUnreachable(URL)
var errorDescription: String? {
switch self {
case .invalidResponse:
return "The server responded with garbage."
case .addressUnreachable(let url):
return "\(url.absoluteString) is unreachable."
}
}
}
// Add your url
let urlRequest = URL(string: "your url")!
// Networking on concurrent queue
let networkQueue = DispatchQueue(label: "Networking",
qos: .default,
attributes: .concurrent)
// Combine network call (This replace your previous code)
func downloadPatients() -> AnyPublisher<Doctor, Error> {
URLSession.shared
.dataTaskPublisher(for: urlRequest)
.receive(on: networkQueue)
.map(\.data)
.decode(type: Doctor.self, decoder: JSONDecoder())
.mapError { (error) -> Network.Error in
switch error {
case is URLError:
return Error.addressUnreachable(self.urlRequest)
default:
return Error.invalidResponse
}
}
.eraseToAnyPublisher()
}
}
现在,在您需要这些值的 SwiftUI 文件中,您只需要调用 downloadPatients() 函数并根据需要使用返回数据:
import SwiftUI
let networkRequest = Network()
//MARK: - Call this function where you want to make your call
func loadPatients() {
_ = networkRequest.downloadPatients()
.sink(
receiveCompletion: {
print("Received Completion: \($0)") },
receiveValue: { doctor in
// doctor is your response and [0].name is your first patient name
print(doctor.patients[0].name) }
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.