Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use JSON arrays with Alamofire parameters?

I'm having a bit of trouble structuring my parameters so that our server API would be able to read it as valid JSON.

Alamofire uses parameters like this in swift language

let parameters : [String: AnyObject] =
[
    "string": str
    "params": HOW I INSERT A VALID JSON ARRAY HERE
]

The problem is that AnyObject does not seem to accept JSON so how would I send / create a structure like this with swift?

{
"string": str, "params" : [
    {
        "param1" : "something",
        "param2" : 1,
        "param3" : 2,
        "param" : false
    },
    {
        "param1" : "something",
        "param2" : 1,
        "param3" : 2,
        "param" : false
    }]
}
like image 427
Miika Pakarinen Avatar asked May 22 '15 10:05

Miika Pakarinen


2 Answers

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
]
]
]
like image 168
Lior Pollak Avatar answered Oct 22 '22 00:10

Lior Pollak


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.

like image 26
Miika Pakarinen Avatar answered Oct 21 '22 22:10

Miika Pakarinen