ios - 在 Swift 中将字典数组作为 JSON 发布

标签 ios json swift ios8 xcode6

我在 Swift 中有两个数组,一个客户数组和一个订单数组。

 var orders = _orderService.GetOrders(...) //just simplifying
 var customers = _customerService.GetCustomers(...) //simplifying obviously

现在我有了 Array 和 Array,我想将它们转换为 JSON,并通过 POST 将它们发送到我的 Web 服务。

我的客户和订单类都有一个 .toDictionary() 实现,允许它们将自己表示为字典,这非常适合 json!

我在想,要正确地将它们一次性表示为 JSON,我可以这样做:

  var customerJSON = customers.map({"\(NSJSONSerialization.dataWithJSONObject($0.toDictionary(), options: nil, error: &err))"})

所以这有效并生成一个字符串数组,数组中的每一行都是一个序列化的客户。我可以对我的订单采用相同的方法,并将它们组合起来生成一个巨大的字符串数组,每个字符串表示为 JSON。

我现在坚持的是如何处理这个数组以正确地发布它。

    request.HTTPMethod = "POST"
    request.HTTPBody = <<WHAT GOES HERE TO SEND VALID JSON OVER??>>
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

非常感谢大家!

最佳答案

就这么简单:

objective-C :

    NSDictionary *data = @{@"orders": orders, @"customers":customers};
    NSData *jsondata = [NSJSONSerialization dataWithJSONObject:data options:0 error:&error];
    [request setHTTPBody:jsondata];

swift :

  let data = ["orders": orders, "customers":customers]
  let jsondata = NSJSONSerialization.dataWithJSONObject(data, options: .allZeros, error: nil)
  request.HTTPBody = jsondata

关于ios - 在 Swift 中将字典数组作为 JSON 发布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27574392/

相关文章:

Python - 从数据框中提取信息 (JSON)

JSON:使用 id 引用 json 模式

javascript - 如何一次显示一个元素?

swift - fatal error : unexpectedly found nil while unwrapping an Optional value - Duc Tran

iOS:UIAlertController 上的 textField 成为出现警报时的第一响应者

ios - 推送后导航栏透明度

iphone - 如何使用 asihttprequest 跟踪单个下载速度

javascript - 防止在包装器应用程序之外访问 Web 应用程序

objective-c - 我的 UINavBar 不响应触摸,并随 tableview 滚动

ios - UIView、Swift 上的深度页面转换