gpt4 book ai didi

json - 如何在 SwiftUI 中访问 json 响应?

转载 作者:行者123 更新时间:2023-12-04 10:21:15 24 4
gpt4 key购买 nike

所以我发出了一个 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) }
)
}

关于json - 如何在 SwiftUI 中访问 json 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60839678/

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