【问题标题】:Posting complex json to api将复杂的 json 发布到 api
【发布时间】:2020-11-06 11:13:58
【问题描述】:

我想发布 json。这是我的参数的样子:

let parameterDictionary = [
    "customer_name": "John Doe",
    "customer_phone": "1234567890",
    "customer_address": "Velit incidunt odit atque quaerat ipsa.",
    "note": "Sequi quisquam ab ea et",
    "datetime_requested": "2020-06-19 09:04:25",
    "products": [
        [
            "id": 53,
            "amount": 15
        ],
        [
            "id": 63,
            "amount": 12
        ]
        
        ]] as [String : Any]

我可以毫无问题地发帖。但是参数是硬编码的。我有一个 Items 结构,其中包含 idamount

struct Items {
    var id: Int
    var amount: Int
}

假设我有这样的物品:

 let items = [Items(id: 53, amount: 12), Items(id: 64, amount: 29)]

如何在我的 parameterDictionary. 中实现这一点?



如果您需要我如何处理发帖:

    let Url = String(format: "https://example.com/api/v1/order")
    guard let serviceUrl = URL(string: Url) else { return }

    var items = [Items(id: 53, amount: 12), Items(id: 64, amount: 29)]
    
    let parameterDictionary = [
    "customer_name": "Didar J",
    "customer_phone": "1234567890",
    "customer_address": "Velit incidunt odit atque quaerat ipsa.",
    "note": "Sequi quisquam ab ea et",
    "datetime_requested": "2020-06-19 09:04:25",
    "products": [
        [
            "id": 53,
            "amount": 15
        ],
        [
            "id": 63,
            "amount": 12
        ]
        
        ]] as [String : Any]
    
    var request = URLRequest(url: serviceUrl)
    request.httpMethod = "POST"
    request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
    guard let httpBody = try? JSONSerialization.data(withJSONObject: parameterDictionary, options: []) else {
        return
    }
    request.httpBody = httpBody
    
    let session = URLSession.shared
    session.dataTask(with: request) { (data, response, error) in
        if let response = response {
            print(response)
        }
        if let data = data {
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: [])
                print(json)
                
            } catch {
                print(error)
            }
        }
        }.resume()

【问题讨论】:

    标签: arrays json swift api posting


    【解决方案1】:

    使用Codable 模型。

    struct Customer: Encodable {
        let customerName, datetimeRequested, customerPhone, note, customerAddress: String
        let products: [Product]
    }
    
    struct Product: Encodable { // or conform existing `Items` model to Enodable
        let id, amount: Int
    }
    

    然后用初始化器构造模型并设置httpBody如下:

    do {
        let encoder = JSONEncoder()
        encoder.keyEncodingStrategy = .convertToSnakeCase
        request.httpBody = try encoder.encode(customer)
    } catch {
        print(error)
    }
    

    【讨论】:

      【解决方案2】:

      对于少数结构成员,我建议使用计算属性将实例映射到字典

      struct Item {
          var id: Int
          var amount: Int
          
          var dictionaryRepresentation : [String:Int] { return ["id":id, "amount":amount] }
      } 
      
      let items = [Item(id: 53, amount: 12), Item(id: 64, amount: 29)]
      let itemArray = items.map{$0.dictionaryRepresentation}
      
      let parameterDictionary = [
      "customer_name": "Didar J",
      "customer_phone": "1234567890",
      "customer_address": "Velit incidunt odit atque quaerat ipsa.",
      "note": "Sequi quisquam ab ea et",
      "datetime_requested": "2020-06-19 09:04:25",
      "products": itemArray] as [String : Any]
      

      【讨论】:

        猜你喜欢
        • 2013-01-18
        • 1970-01-01
        • 2020-03-15
        • 2016-11-06
        • 1970-01-01
        • 2014-09-02
        • 2014-09-11
        • 2011-07-07
        • 2018-07-12
        相关资源
        最近更新 更多