Hi,
I have a struct that I'd like to encode with JSON and send in the body of an HTTP request:
struct AccountCreationData: Codable, Hashable {
var name: String
var email: String
var phone: String
var password: String
private enum CodingKeys: String, CodingKey {
case name
case email
case phone
case password
}
}
I encode it with this code and set the HTTP request body to the encoded data:
guard let encoded = try? JSONEncoder().encode(account) else {
print("Failed to encode request")
return
}
request.httpBody = encoded
But in my backend, when I receive the data from the HTTP request, the JSON data is formatted as such:
'{"phone":"0000000000",
"password":"password",
"email":"email",",
"name":"name"}': ''}
Instead of:
{
"phone": "0000000000",
"password":"password"
"email":"email"
"name":"name"
}
So the JSON parser in my backend isn't properly parsing the data because of the format that the JSON is in. I was wondering if this is an issue with the way I'm encoding on the front end (Swift) or my backend. I have similar projects using the same code to encode the data so I'm unsure as to what the issue is. Any help would be greatly appreciated. Thank you.
AccountCreationData(name: "name", email: "email", phone: "phone", password: "password")
110 bytes
Something is off. Testing here, if I encode your struct with those exact values, the result is 69 bytes, not 110 bytes. Can you print out a string representation of the encoded JSON?
And separately, do you need to set a Content-Type: application/json
header so your server knows that the body format is JSON?