概括
我正在嘗試從 API 獲取資料并將其解碼為 json
我對以下代碼有 2 個問題
apiOutput 變數的輸出是否適合解碼為 json 格式,如果不是,我如何獲得正確的輸出?我在想它可能會改變選項
JSONSerialization.jsonObject
如何將我的
apiOutput
變數提供給我希望能夠將 apiOutput 解碼為正確的 json 格式的 PriceApiModel.swift。即使 PriceApiModel.swift 能夠做到這一點,我也不確定如何將 apiOutput 輸入其中
此影像是 API 回傳的資料
我在呼叫 API 資料后嘗試獲取它,請參閱下面的完整代碼
// from AppDelegate.swift full file included below
let apiOutput = try JSONSerialization.jsonObject(with: data!, options: [])
print(apiOutput) // please see output below
列印 apiOutput 的輸出
{
askPrice = "0.07530300";
askQty = "28.15780000";
bidPrice = "0.07530200";
bidQty = "20.99700000";
closeTime = 1666814307216;
count = 389744;
firstId = 383543634;
highPrice = "0.07593900";
lastId = 383933377;
lastPrice = "0.07530300";
lastQty = "11.85740000";
lowPrice = "0.07230700";
openPrice = "0.07365100";
openTime = 1666727907216;
prevClosePrice = "0.07365200";
priceChange = "0.00165200";
priceChangePercent = "2.243";
quoteVolume = "13084.96427533";
symbol = ETHBTC;
volume = "176432.41160000";
weightedAvgPrice = "0.07416418";
}
我制作了 PriceApiModel.swift 來嘗試解碼上述輸出。但是不要相信我在 JSONSerialization 中有正確的選擇,因為輸出看起來更像變數而不是 json 檔案。
// PriceApiModel.swift
import Foundation
import SwiftUI
import CoreLocation
struct PriceApiModel: Hashable, Codable {
var askPrice: String
var askQty: String
var bidPrice: String
var bidQty: String
var closeTime: Int
var count: Int
var firstId: Int
var highPrice: String
var lastId: Int
var lastPrice: String
var lastQty: String
var lowPrice: String
var openPrice: String
var openTime: Int
var prevClosePrice: String
var priceChange: String
var priceChangePercent: String
var quoteVolume: String
var symbol: String
var volume: String
var weightedAvgPrice: String
}
AppDelegate.swift 的完整代碼
import UIKit
class ViewController: UIViewController {
let headers = [
"X-RapidAPI-Key": "cannot provide this please see sample outpout",
"X-RapidAPI-Host": "binance43.p.rapidapi.com"
]
let request = NSMutableURLRequest(url: NSURL(string: "https://binance43.p.rapidapi.com/ticker/24hr?symbol=ETHBTC")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
func getData() {
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? HTTPURLResponse
do {
let apiOutput = try JSONSerialization.jsonObject(with: data!, options: [])
print(apiOutput) // this is the output I am getting
} catch {
print("NOT WORKING ")
}
}
})
dataTask.resume()
}
}
uj5u.com熱心網友回復:
如果您只想將接收到的資料解碼到您的模型中,您可以使用JSONDecoder
.
let model = try JSONDecoder().decode(PriceApiModel.self, from: data!)
但是,如果您想在代碼中進一步使用此模型,我建議您對收到的資料使用一些有用的型別。我做了一個例子,askPrice
但其他人將以類似的方式完成。
// used for throwing errors
enum CustomError: Error{
case decodingError
}
struct PriceApiModel: Hashable, Codable {
//changed the String type to Decimal
var askPrice: Decimal
var askQty: String
var bidPrice: String
var bidQty: String
var closeTime: Int
var count: Int
var firstId: Int
var highPrice: String
var lastId: Int
var lastPrice: String
var lastQty: String
var lowPrice: String
var openPrice: String
var openTime: Int
var prevClosePrice: String
var priceChange: String
var priceChangePercent: String
var quoteVolume: String
var symbol: String
var volume: String
var weightedAvgPrice: String
// every property you are interested to decode needs a CodingKey.
// You can omit values you are not interested in
enum CodingKeys: CodingKey{
case askPrice
}
// here you decode your data into the struct
init(from decoder: Decoder) throws {
// get the container
let container = try decoder.container(keyedBy: CodingKeys.self)
// decode the askPrice into a String and cast it into a Decimal
let askPrice = Decimal(string: try container.decode(String.self, forKey: .askPrice))
// check if casting was succesfull else throw
guard let askPrice = askPrice else{
throw CustomError.decodingError
}
// assign it
self.askPrice = askPrice
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/522255.html
標籤:迅速
上一篇:任務@Sendable操作