Search code examples
swiftalamofireswifty-jsonobjectmapper

How to post nested json by objectMapper and Alamofire?


I am having request json for the post API :

{"TokenId": "xxxxxx-xxxxx-xxxx-xxx", 
"ObjSearch": 
  {

     "UserId":"0",
     "FromDate":"",
     "StateId":"0",
     "DistrictId":"0",
     "ToDate":""
  }
}

currently I have created two request models like:

class  ChartsReqModel: NSObject, Mappable {
  var TokenId:String?
  var ObjSearch : [ChartObjSearchReqModel]?
}

AND

class  ChartObjSearchReqModel: NSObject,Mappable {
var FromDate:String?
var ToDate:String?
var StateId:String?
var DistrictId:String?
var UserId:String?
var ProductId:String?
var SalesChannelId:String?
var ReporteesId:String?
var `Type`:String?

func mapping(map: Map) {
    FromDate <- map["FromDate"];
    ToDate <- map["ToDate"];
    StateId <- map["StateId"];
    DistrictId <- map["DistrictId"];
    UserId <- map["UserId"];
    ProductId <- map["ProductId"];
    SalesChannelId <- map["SalesChannelId"];
    ReporteesId <- map["ReporteesId"];
    Type <- map[![\[][1]][1]"Type"];
}
}

the Desired response I am getting from my API in postman looks perfect but I think from my code I am unable to send the correct request model and for the my Data shows

Data = ( );

I am new to Swift and I am not able to find out the problem in the code.. please someone help me to find the solution

Screenshot of POSTMAN:


Solution

  • Based on the request structure, below is the simplified way to encode/decode ChartsReqModel object,

    class  ChartsReqModel: NSObject, Mappable {
      var TokenId:String?
      var ObjSearch: ChartObjSearchReqModel?
    
      required init?(map: Map) {}
    
      func mapping(map: Map) {
          self.TokenId    <- map["TokenId"]
          self.ObjSearch  <- map["ObjSearch"]
      }
    }
    

    Now when you have json from the response, you can decode ChartsReqModel object by passing that json as below,

    let chartsObject = ChartsReqModel(JSON: jsonFromResponse)
    

    And when you want to post the ChartsReqModel json, you can encode it as below

    let paramsJson = chartsObject.toJSON()