Preeti Rani Preeti Rani - 5 months ago 34
JSON Question

Convert Arraylist of some Class type into JSON format using Swift

I want to hit an api using Alamofire in which I have to pass parameters as :

"reminder":
[
{
"isAlarmOn": "true",
"time": "06:29 PM"
},
{
"isAlarmOn": "true",
"time": "06:30 AM"
}
]


For achieving this, I Created an Array as

var reminderArray : [AlarmRequestModel] = [AlarmRequestModel]()


where AlarmRequestModel is Like ,

AlarmRequestModel.swift

import Foundation
class AlarmRequestModel {
var time : String = "12:00 PM"

init(time : String){
if !time.isEmpty{
self.time = time
}

}
}


and filled reminderArray as

func setArray() {
reminderArray.insert(AlarmRequestModel(time: "5:00 PM"), atIndex: 0)
reminderArray.insert(AlarmRequestModel(time: "6:00 PM"), atIndex: 1)
reminderArray.insert(AlarmRequestModel(time: "7:00 PM"), atIndex: 2)
reminderArray.insert(AlarmRequestModel(time: "8:00 PM"), atIndex: 3)
}


And while hitting the Api , I Declared the parameters as

func hitApi()
{
let parameters : [String:AnyObject] = [
"reminder" : reminderArray.description,
]

print("parmeters : \(parameters)")
}


But I didn't get the expected output ,
the output was like ->

parmeters :["reminder": [My_Swaasth.AlarmRequestModel,My_Swaasth.AlarmRequestModel,My_Swaasth.AlarmRequestModel,My_Swaasth.AlarmRequestModel]]


Please anyone Suggest , What changes Do I Need to do in order to achieve the desired output.

Answer

There is a protocoll called CustomStringConvertible which has the

var description: String property

But that won't result the desired output. So I'd rather implement a parameter value for AlarmRequestModel

extension AlarmRequestModel {
     var parameterValue: Dictionary<String, String> {
         return ["isAlarmOn": "true", "time": self.time]
     }
}

And use this like

reminderArray.map() { reminder in return reminder.parameterValue }

here:

    let parameters  : [String:AnyObject] = [
        "reminder" : reminderArray.map() { reminder in return reminder.parameterValue },
        ]
Comments