加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何在Swift3中将总模型对象作为Alamofire post方法的参数发送?

发布时间:2020-12-14 05:48:49 所属栏目:百科 来源:网络整理
导读:我有这样的模型类 class Example() { var name:String? var age:String? var marks:String? } 我正在向该模型类添加数据 let example = Example()example.name = "ABC"example.age = "10"example.marks = "10" 之后我转换为JSON然后我发布了 Alamofire.reque
我有这样的模型类
class Example() {
  var name:String?
  var age:String?
  var marks:String? 
}

我正在向该模型类添加数据

let example = Example()
example.name = "ABC"
example.age = "10"
example.marks = "10"

之后我转换为JSON然后我发布了

Alamofire.request(URL,method:.post,parameters: example)

Alamofire不接受参数只接受类似参数= [“”:“”,“”,“”] – >基于键值,所以我试图将模型转换为JSON,JSON转换为字典,即使不接受它的显示喜欢参数问题.我需要总模型对象需要在Alamofire中作为post方法的参数发送,如下所示:

let example = Example()
Alamofire.request(URL,parameters: example)
由于Alamofire API只接受字典,因此请自行创建字典!

在模型类中添加一个名为toJSON的方法:

func toJSON() -> [String: Any] {
    return [
        "name": name as Any,"age": age as Any,"marks": marks as Any
    ]
}

然后在调用request时调用此方法:

Alamofire.request(URL,method:.put,parameters:example.toJSON(),encoding:JSONEncoding.default,headers :Defines.Api.Headers )

或者,使用SwiftyJSON:

func toJSON() -> JSON {
    return [
        "name": name as Any,"marks": marks as Any
    ]
}

用法:

Alamofire.request(URL,parameters:example.toJSON().dictionaryObject,headers :Defines.Api.Headers )

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读