I have a very simple model struct
Student
which only has two properties firstName
and lastName
:
struct Student {
let firstName: String
let lastName: String
init(_ firstName: String, _ lastName: String) {
self.firstName = firstName
self.lastName = lastName
}
// Convert to json data
func toData() -> Data? {
var json = [String: Any]()
let mirror = Mirror(reflecting: self)
for child in mirror.children {
if let key = child.label?.trimmingCharacters(in: .whitespacesAndNewlines) {
json[key] = child.value
}
}
do {
return try JSONSerialization.data(withJSONObject: json, options: [])
} catch {
print("\(error.localizedDescription)")
}
return nil
}
}
As you see above, I created an toData()
function which I use to convert model object to JSON data for my HTTP request body.
I create Student
instance by:
let student = Student("John", "Smith")
I got Json Data by:
let jsonData = student.toData()
later I set to my URLRequest
body by:
request.httpBody = jsonData!
However, backend team always see :
{\"firstName\":\"John\", \"lastName\":\"Smith\"}
But backend expect:
{"firstName":"John", "lastName":"Smith"}
I am sure it is not backend problem. Looks like something needs to improve in my toData()
function. But I don't know what to do. Could someone help me?