簡體   English   中英

如何在 SwiftUI 中訪問 json 響應?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM