【发布时间】:2019-03-29 19:43:27
【问题描述】:
我需要按以下顺序将 json 发送到服务器
data:{"firstname":"Alpha","lastname":"Beta"}
在此数据键在 json 之外,如 [data:json],但是当我序列化时,它将请求作为
{
"data" : {
"firstname" : "alpha",
"lastname" : "beta"
}
}
这些是我的模型:
struct UserDetail :Codable {
let data :CreateProfileModel
}
struct CreateProfileModel :Codable {
let firstname :String
let lastname :String
}
我在这些模型中添加的数据
let profileInfo = CreateProfileModel(firstname: "alpha" , lastname: "beta")
let userDetails = UserDetail(data: profileInfo)
这是我使用 swift 进行的 json 编码:
let jsonEncoder = JSONEncoder()
jsonEncoder.outputFormatting = .prettyPrinted
do{
let userData = try jsonEncoder.encode(userDetails)
print(String(data: userData, encoding: .utf8)!)
networkListener.requestPost(endpoint: endpoint, data: userData , headerValue: nil)
}catch{
print(error)
}
在 requestPost 方法中
func requestPost(endpoint : String , data :Data,headerValue : String?){....
request.httpbody = data
}
我将该数据添加到request.httpbody。
如何使用 profileInfo 添加数据键?
【问题讨论】:
-
为什么不直接将 JSON 作为参数发送,而不将其放入字典中?
标签: ios json swift xcode swift4