将Alamofire结果分配给数组

问题描述 投票:0回答:1

我正试图将Alamofire检索到的结果分配给一个数组,并遇到了一个问题。

我使用Stripe API来处理产品,它返回了一个名为 "data: "的JSON对象,我试图将该数据对象仅分配给我拥有的产品数组。

下面是我的代码

var products: [Product] = []
let stripeProducts = "stripe-products-api"

func createArray() {
  let stripeAuthHeader: HTTPHeaders = []

  AF.request(stripeProducts, headers: stripeAuthHeader).responseJSON {
     switch response.result {
     case .failure(let error):
       print(error)
     case .success:
       self.products = response.data \\ trying to access the data object from the JSON data
       print(self.products)
     }
  }
}

JSON。


 "object": "list",
  "data": [
    {
      "id": "prod_123456",
      "object": "product",
      "active": true,
      "attributes": [

      ],
      "created": 1590423835,
      "description": "Test",
      "images": [
        ""
      ],
      "livemode": false,
      "metadata": {
        "address": "Test"
      },
      "name": "Blue Jeans",
      "statement_descriptor": null,
      "type": "service",
      "unit_label": null,
      "updated": 1590653248
    }
]

谢谢你的帮助。

arrays swift alamofire
1个回答
0
投票

你需要有产品的结构

  struct Datum: Decodable {
    let id, object: String
    let active: Bool
    let created: Int
    let datumDescription: String
    let images: [String]
    let livemode: Bool
    let metadata: Metadata
    let name: String
    let type: String
    let updated: Int

    enum CodingKeys: String, CodingKey {
        case id, object, active, created
        case datumDescription = "description"
        case images, livemode, metadata, name
        case type
        case updated
    }
}

// MARK: - Metadata
struct Metadata: Decodable {
    let address: String
}

然后这样解析

let products = try? newJSONDecoder().decode(Products.self, from: response.data)
© www.soinside.com 2019 - 2024. All rights reserved.