How do I use JSON arrays with Alamofire parameters?

怎甘沉沦 提交于 2019-11-30 20:54:23

Taken from Alamofire's GitHub page:

let parameters = [
    "foo": [1,2,3],
"bar": [
    "baz": "qux"
]
]

Alamofire.request(.POST, "http://httpbin.org/post", parameters: parameters, encoding: .JSON)
// HTTP body: {"foo": [1, 2, 3], "bar": {"baz": "qux"}}

EDIT: And from your example:

let parameters = [
    "string": "str",
"params": [[
    "param1" : "something",
    "param2" : 1,
    "param3" : 2,
    "param" : false
],[
    "param1" : "something",
    "param2" : 1,
    "param3" : 2,
    "param" : false
]
]
]

Solved this myself. I can just do

    parameters =
    [
        "params": array
    ]

Where array is Dictionary (String, AnyObject). The problem I initially had with this solution was that you can't insert booleans into this kind of dictionary, they will just be converted into integers. But apparently alamofire JSON encoding (I think) sends them as true/false values nevertheless.

You need to create a NSArray object for array parameters.

var yourParameters = [
  "String": "a string",
  "Int": 1,
  "Array": NSArray(
    array: [
        "a", "b", "c"
    ])
]

Swift 2.2 and using SwiftyJSON.swift
You can use like this.

    var arrayList : [String: AnyObject]//one item of array

    var list: [JSON] = []//data array 

    for i in 0..<10//loop if you need
    { 

        arrayList = [
            "param1":"",
            "param1":"",
            "param2":["","",""]
        ]

        list.append(JSON(arrayList))//append to your list

    }


    //params
    let params: [String : AnyObject]=[

        "Id":"3456291",
        "List":"\(list)"//set
    ]

In case, there is a need to pass array directly as a parameter for a alamofire request, the following method worked for me.

source: https://github.com/Alamofire/Alamofire/issues/1508

let headers = NetworkManager.sharedInstance.headers
var urlRequest = URLRequest(url: URL(string: (ServerURL + Api))!)
urlRequest.httpMethod = "post"
urlRequest.allHTTPHeaderFields = headers
let jsonArrayencoding = JSONDocumentArrayEncoding(array: documents)
let jsonAryEncodedRequest = try? jsonArrayencoding.encode(urlRequest, with: nil)

    var request: Alamofire.DataRequest? = customAlamofireManager.request(jsonAryEncodedRequest!)
    request?.validate{request, response, data in
        return .success
        }
        .responseJSON {

if you are using SwiftyJSON, you can write like this

let array = ["2010-12-13T5:03:20","2010-12-13T5:03:20"]
 let paramsJSON = JSON(array)
 var arrString = paramsJSON.rawString(NSUTF8StringEncoding)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!