使用alamofire发布带有字典和字典数组的JSON对象

时间:2017-03-28 17:51:28

标签: ios json swift alamofire

我试图像这样发布一个对象:

{
  "simulation" : { },
  "simOptions" : [
    { },
    { }
  ]
}

并尝试通过调用我的SimulationRepository类发布它:

SimulationsRepository().confirmSimulation(params: parameters) { (response) in
  if let error = checkError(response) {
    self.hideLoading()
    self.showAlert(error)
    return
  }

  guard let simsArray = SimulacaoArray(responseObject: response.result.value) else {        
    let error = response.error.debugDescription      
    self.hideLoading()
    self.showAlert(error)        
    return
  }

  print(simsArray.simulation.count)
}

我已经在Sending json array via AlamofireAlamofire: Send JSON with Array of Dictionaries尝试了解决方案,但无法正确转换字典数组。

1 个答案:

答案 0 :(得分:0)

好的我已经解决了maping模拟商品数组并将其转换为字典,如下所示:

class SimulationsRepository: BaseRepository {

  init() {
    super.init(url: "/Simulations")
    super.BaseUrl = "http://0.0.0.0:3000/api"
  }

  func confirmSimulation(simulation: Simulation, goods: [SimulatedGoods], then: @escaping ThenBlock) {
    let goodsDict = goods.map { (simulatedGoods) -> [String: Any] in
      return simulatedGoods.toDictionary()
    }
    let sim = simulation.toDictionary()

    let params: [String: Any] = [
      "simulation": sim,
      "goods": goodsDict
    ]
    super.customPost("/confirm", parameters: params, then: then)
  }

}

顺便说一下,我从书中得到了像这样编组数组的想法:https://www.hackingwithswift.com/store/pro-swift