Prabhu
Prabhu

Reputation: 13325

Serializing an array before sending it to an API end point

I am sending an array to an API endpoint, but the array is not going throuhg correctly. Here is what I have:

User: name email

So in my case I have a swift array of two users:

po userArray
▿ 2 elements
  ▿ [0] : <User: 0x7fa3ab597fd0>
  ▿ [1] : <User: 0x7fa3ab597bb0>

The JSON that the server expects is:

{users: [ {name:'john', email:'[email protected]'}, {name:'tom', email: '[email protected]' }]

What I'm sending:

'users' : userArray

But there seems to be a serialization issue. What the server is getting from me is this:

'users': ['MyApp.User', 'MyApp.User']

I'm using AlamoFire to send my PUT request.

Do I need to do convert the array to JSON before sending it out? I'm new to Swift and any help is appreciated.

Upvotes: 0

Views: 64

Answers (2)

Amit Singh
Amit Singh

Reputation: 2698

You need to override description property for the custom class User

class User : NSObject
{ 
   var name : String
   var age : String

   override var description : String
   {
      get{
         return ["name" : self.name, "age" : self.age].description
      }
   }
}

Upvotes: 1

Volodymyr
Volodymyr

Reputation: 1205

You need to convert your User object into dictionary. Than you should add as value not array of users, but array of dictionaries.

Upvotes: 2

Related Questions