How to send json data with json object in swift 4

Viewed 2281

I need to send json to server in following order

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

enter image description here

In this the data key is outside of json like [data:json] but when I am serialization it making the request as

{
  "data" : {
    "firstname" : "alpha",
    "lastname" : "beta"
  }
}

These are my models :

struct UserDetail :Codable {
    let data :CreateProfileModel
}

struct CreateProfileModel :Codable {
    let firstname :String
     let lastname :String
}

Data I am adding in these models

let profileInfo = CreateProfileModel(firstname: "alpha" , lastname: "beta")

let userDetails = UserDetail(data: profileInfo)

This is the json encoding that I am doing using swift :

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

In requestPost method

  func requestPost(endpoint : String , data :Data,headerValue : String?){....
  request.httpbody = data
}

I am adding that data the request.httpbody.

How can i add data key with profileInfo ?

2 Answers

If the API requires (effectively) HTML form data, you'll need to construct the body yourself and extract bits of JSON.

Try:

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)

Try this Code:

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