我有一个非常简单的模型struct
Student
,它只有两个属性firstName
和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
}
}
如上所述,我创建了一个toData()
函数,用于将模型对象转换为HTTP请求正文的JSON数据。
我通过以下方式创建Student
个实例
let student = Student("John", "Smith")
我得到了Json Data:
let jsonData = student.toData()
后来我通过以下方式设置了URLRequest
身体
request.httpBody = jsonData!
然而,后端团队总是看到:
{\"firstName\":\"John\", \"lastName\":\"Smith\"}
但后端期望:
{"firstName":"John", "lastName":"Smith"}
我确信这不是后端问题。看起来我的toData()
函数需要改进一些东西。但我不知道该怎么做。有人能帮助我吗?
答案 0 :(得分:0)
试试这个:
if let jsonString:String = String(data: jsonData!, encoding: String.Encoding.utf8) {
request.httpBody = jsonString.data(using: String.Encoding.utf8)
}
答案 1 :(得分:0)
您可以通过手动将结构转换为字典来消除额外的反斜杠。
我使用虚拟休息服务器(rest-server-dummy from npm)测试了以下方法,并且"" 字符周围没有额外的反斜杠。
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]()
json["firstName"] = firstName
json["lastname"] = lastName
do {
return try JSONSerialization.data(withJSONObject: json, options: [])
} catch {
print("\(error.localizedDescription)")
}
return nil
}
}
我使用此方法将数据发送到在localhost上运行的虚拟服务器:
var request = URLRequest(url:URL(string: "http://localhost:8080/username")!)
request.httpMethod = "POST"
request.httpBody = student.toData()
URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
data
response
error
}).resume()
服务器日志输出的内容:
{
"lastname": "Smith",
"firstName": "John"
}