使用Alamofire

时间:2018-04-14 19:29:22

标签: ios json swift alamofire

我目前正在开发iOS应用程序,最近我遇到了一个障碍,基本上我尝试使用的API端点需要一个JSON对象作为这种格式的POST参数。

{
  json: {
    product_report: [
      {
        "id_assigned_pos": someid,
        "id_user": someid,
        "number": somenumber,
      },
      {
        "id_assigned_pos": someid,
        "id_user": someid,
        "number": somenumber,
      },{
        "id_assigned_pos": someid,
        "id_user": someid,
        "number": somenumber,
      }
    ]
  }
}

我很难弄清楚如何使用Alamofire和swift 4实现这一目标。 我很感激别人的帮助。 谢谢!

2 个答案:

答案 0 :(得分:1)

let parameters = [
    "json": [
        "product_report": [
            [
                "id_assigned_pos": 1,
                "id_user": 1,
                "number": 1
            ],
            [
                "id_assigned_pos": 1,
                "id_user": 1,
                "number": 1
            ],
            [
                "id_assigned_pos": 1,
                "id_user": 1,
                "number": 1
            ],
        ]
    ]
]


Alamofire.request(url, method:.post, parameters:parameters, headers:headers).responseJSON { response in
    // Here is the response  
} `

答案 1 :(得分:-1)

  

你可以尝试这个:

var dict : [String: Any] = [:]

dict["type"] = "Step"
dict["data"] = ["2015-08-02": 8574];

let params: [String: Any] = ["r_id": "someName",
                            "data": String.jsonString(data: dataDict)];

这里jsonString是String

的扩展
static func jsonString(data : Any) -> String {

        var jsonString = "";

        do {

            let jsonData = try JSONSerialization.data(withJSONObject: data, options: .prettyPrinted)
            jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)! as String

        } catch {
            print(error.localizedDescription)
        }

        return jsonString;
}