![](/img/trans.png)
[英]How to make GET API calls that has large JSON response in Swift 5?
[英]iOS Swift 5 API Response isn't JSON, it has semicolons?
我正在嘗試使用一個API響應,該響應在郵遞員中很好地返回,但是當我快速打印時,它在行尾有分號
我嘗試了各種選項以及各種更改請求和處理響應的方法,但均無濟於事。 為什么分號在那里?
*******代碼段******
let todosEndpoint: String = "https://url:3000/api/v1/somestring?
query=$filter%3DUPC%20eq%20'somenumber'"
guard let todosURL = URL(string: todosEndpoint) else {
print("Error: cannot create URL")
return
}
var todosUrlRequest = URLRequest(url: todosURL)
todosUrlRequest.httpMethod = "GET"
todosUrlRequest.setValue("application/json", forHTTPHeaderField:
"Content-Type")
todosUrlRequest.setValue("Bearer "+token, forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: todosUrlRequest) { (data, response, error) in
guard let dataResponse = data,
error == nil else {
print(error?.localizedDescription ?? "Response Error")
return }
do{
let myJson = try JSONSerialization.jsonObject(with: data!) as? NSDictionary
print(myJson!)
********結果*****
Desired Results:
{
"@odata.context": "https://api.url.com/v1/$metadata#Products",
"value": [
{
"ASIN": null,
"Height": null,
"Length": null,
"Width": null,
"Weight": null,
"Cost": null,
"Margin": null,
"RetailPrice": null,
"StartingPrice": null,
"ReservePrice": null,
}
]
}
Actual Results:
{
"@odata.context" = "https://api.url.com/v1/$metadata#Products";
value = (
{
ASIN = "<null>";
BlockComment = "<null>";
BlockedDateUtc = "<null>";
Brand = BAZZILL;
BundleType = None;
BuyItNowPrice = "0.99";
CategoryCode = "<null>";
CategoryPath = "<null>";
Classification = "<null>";
Condition = "<null>";
Cost = "<null>";
}
);
}
如果您將JSON序列化為字典是因為您正在執行以下操作:
let myJson = try JSONSerialization.jsonObject(with: data!) as? NSDictionary
print(myJson!)
這意味着您可以像訪問每個字段一樣: let comment = myJson["BlockComment"]
但是,最好序列化為結構:
struct Product: Codable {
let asin: String?
let blockComment: String?
let brand: String?
let buyItNowPrice: Float?
let cost: Float?
enum CodingKeys: String, CodingKey {
case asin = "ASIN"
case blockComment = "BlockComment"
case brand = "Brand"
case buyItNowPrice = "BuyItNowPrice"
case cost = "Cost"
}
}
然后您將執行以下操作:
let product = try JSONDecoder().decode(Product.self)
print(product.cost)
print(product.brand)
//etc..
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.