如何通过objectMapper和Alamofire发布嵌套的json?

时间:2018-05-15 12:43:05

标签: swift alamofire swifty-json objectmapper

我正在为post API请求json:

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

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

目前我创建了两个请求模型,如:

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

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"];
}
}

我从邮递员的API中获得的所需响应看起来很完美,但我想从我的代码中我无法发送正确的请求模型和我的数据显示

  

数据=(       );

我是Swift的新手,我无法在代码中找到问题。 请有人帮我找到解决方案

POSTMAN的屏幕截图:

1 个答案:

答案 0 :(得分:1)

根据请求结构,下面是编码/解码ChartsReqModel对象的简化方法,

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"]
  }
}

现在当您从响应中获得json时,您可以通过传递json来解码ChartsReqModel对象,

let chartsObject = ChartsReqModel(JSON: jsonFromResponse)

如果您想发布ChartsReqModel json,可以将其编码为

let paramsJson = chartsObject.toJSON()