【问题标题】:How to send json data with json object in swift 4如何在 swift 4 中使用 json 对象发送 json 数据
【发布时间】: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


【解决方案1】:

如果 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)

【讨论】:

  • userData 的类型是 Data 而不是 String,因此帖子正文将变成一个字符串,我无法将其作为 Data 传递给 requestPost 方法。
【解决方案2】:

试试这个代码:

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)
  }

【讨论】:

    猜你喜欢
    • 2014-04-07
    • 2015-12-30
    • 2019-06-10
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    • 2018-04-10
    • 2021-02-27
    • 1970-01-01
    相关资源
    最近更新 更多