Michał Jurczuk
Michał Jurczuk

Reputation: 3828

Easily serialize an object to JSON

How do I serialize an Swift object to JSON, the following object for example :

class Order {

   var id:Int
   var title:String
   var email:String

   init(id:Int, title:String, email:String) {
      self.id = id
      self.title = title
      self.email = email
   }
}

let order = Order(id:345, title:"Title", email:"[email protected]")

Currently I tried creating a SwiftyJSON JSON object like so but it still requires me to manually specify each property :

let json = JSON()
json["id"] = order.id
json["title"] = order.title
json["email"] = order.email

Moreover, that doesn't help me as Alamofire doesn't understand SwiftyJSON's objects, requiring me to create a dictionary manually :

let dict:[String, AnyObject] = [
    "id":order.id,
    "title":order.title,
    "email":order.email
]

Alamofire.request(.POST, Configuration.ADD_ORDER_URL, parameters: dict, encoding:.JSON)

To recap, how can I serialize an object to JSON and send it off right away using Alamofire ?

Upvotes: 1

Views: 4195

Answers (2)

Jesus Rodriguez
Jesus Rodriguez

Reputation: 2621

I had the same problem but and it took me way too long to find this out.

However, user2629998's response is correct. In the OP's case he is using a dictionary so he needs to declare like so:

let parameters:[String : AnyObject] = []

Also, you have to declare the header

let headers = ["Content-Type": "application/json"]

which later must be passed to the alamofire request

Alamofire.request(.POST, yourEndpoint, headers:headers, parameters: parameters, encoding: .JSON)

I decided to elaborate more on user2629998 because the header can make a difference.

Also, I wanted to point out that this can be non-intuitive for many users as I noticed when searching through different questions regarding this issue or similar problems. Why? because even when you want to send a JSON, you can not do that in Alamofire. So basically, Alamofire takes care of it under the hood. Hence, you're are forced to send the dictionary and make use of Alamofire's neat features.

Upvotes: 2

user2629998
user2629998

Reputation:

From the Alamofire documentation :

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

Alamofire.request(.POST, "http://httpbin.org/post", parameters: parameters, encoding: .JSON)

You create an array representing your JSON, and then set the encoding argument to Alamofire.JSON. SwiftyJSON has nothing to do here, as it only deals with deserializing a JSON response.

Upvotes: 1

Related Questions