Search code examples
jsonswiftmodelobjectmapper

How to map JSON String to model class using Object Mapper in swift


My model class is like:

class CalendarTaskModel: Mappable {

     var kpiColor: String?
     var kpi: String?
     var date: String?

     required init?(map: Map) {
        //Code here
     }

    func mapping(map: Map) {
         kpiColor <- map["kpiColor"]
         kpi <- map["kpi"]
         date <- map["date"]
     }
 }

I have an object mapped with a model class.

var taskDetails: [CalendarTaskModel]?

As my object is of array type so I Want to map JSON string to object using ObjectMapper like the code below.

code 1: taskDetails = Mapper<[CalendarTaskModel]>().map(JSONString: jsonStr)
//
code 2: taskDetails = Mapper<CalendarTaskModel>().map(JSONString: jsonStr)

but I am getting errors enter image description here && enter image description here Please suggest how to do this? Thanks in advance.


Solution

  • I figured it out! You should use the mapArray method instead:

    let jsonStr = ...
    var taskDetails: [CalendarTaskModel]?
    taskDetails = Mapper<CalendarTaskModel>().mapArray(JSONfile: jsonStr)
    

    This is because the map method does not return an array.

    As for the code 1 that you provided, the [CalendarTaskModel] type (equivalent to Array<CalendarTaskModel> is not compliant with that mappable protocol. I suspect it is possible to make it compliant, for instance with more complex logic, but the library encourages you to use the method I suggested. Best of luck!