Home > Net >  swift JSONEncoder generate not valid data
swift JSONEncoder generate not valid data

Time:11-29

I have a simple string in swift:

let str = "{"phone": " 79217463536","name": "skjfhkjdhg","username": "ksfhksdjhf"}"

I generate Data:

let data = str.data(.utf8)

and then send data to request.httpBody = data, and then send post request.

When swift transforms string to data, it adds a character "\", and server dont understand my json.

"{\"phone\": \" 79217463536\",\"name\": \"skjfhkjdhg\",\"username\": \"ksfhksdjhf\"}"

In python it work good. Help me please, I need to transform string to data without any symbols, or I need to send request without data, and with string.

CodePudding user response:

Don´t create the data this way, it is error prone. And there is a better way.

  1. Create a struct that holds your data:

    struct Model: Codable{
        let name: String
        let phone: String
        let username: String
    }
    
  2. Instantiate the model with appropriate values:

    let model = Model(name: "name here", phone: "phone here", username: "username here")
    
  3. Create the data from this model:

    let data = try JSONEncoder().encode(model)
    

Then send this data via the URLRequest.

And you should add the contenttype header. Else your api won´t understand what your are sending.

let url = URL(string: "plannerok.ru/api/v1/users/register/") 
var request = URLRequest(url: url!) 
request.httpMethod = "POST" 
request.httpBody = data
// add this
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared 
  • Related