如何在Swift 4

时间:2018-10-25 08:49:49

标签: ios json swift xcode swift4

我需要按照以下顺序将json发送到服务器

data:{"firstname":"Alpha","lastname":"Beta"}

enter image description here

在这种情况下,数据密钥位于[data:json]之类的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添加数据密钥?

2 个答案:

答案 0 :(得分:0)

如果API需要(有效)HTML表单数据,则需要自己构造主体并提取JSON位。

尝试:

let userData = try jsonEncoder.encode(userDetails.data)
let postBodyString = "data:\(userData)"
let postBodyData = postBodyString.data(using: String.Encoding.utf8)
networkListener.requestPost(endpoint: endpoint, data: postBodyData, headerValue: nil)

答案 1 :(得分:0)

尝试以下代码:

var columnValus:[String:Any]  = [:]

columnValus["firstname"] = userDetails.data.firstname
columnValus["lastname"] = userDetails.data.lastname

let userData = [
      "data": columnValus
      ] as [String : Any]

  do {
      let postData = try JSONSerialization.data(withJSONObject: userData, options: [])
      networkListener.requestPost(endpoint: endpoint, data: postData , headerValue: nil)
  }catch let error as NSError {
      print(error)
  }