我正在尝试学习JSON解析。我已经用Laravel编写了一个API,它返回status : 200作为响应。我做的是这样的:
guard let url = URL(string: "http://localhost/workon-api/public/api/register") else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let newUser = User.init(name: "Rob", email: "abc@gmail.com", password: "12345678")
do {
let jsonBody = try JSONEncoder().encode(newUser)
request.httpBody = jsonBody
} catch { }
URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let data = data else { return }
do {
let json = try JSONSerialization.data(withJSONObject: data, options: .prettyPrinted)
print(json)
} catch {}
}.resume()现在,我得到了这个错误:Invalid top-level type in JSON write和应用程序崩溃。在搜索之后,我使用了这个:
let json = try JSONSerialization.jsonObject(with: data, options: [])而且,它是有效的。为什么之前的方法不起作用?并且,如果我试图返回收集的userInfo,我会得到类似这样的响应。
status = "{\"name\":\"Rob\",\"email\":\"abc@gmail.com\",\"password\":\"12345678\"}";为什么会有反斜杠?这些可以吗?那么,什么是Gzip数据呢?我知道我的要求太多了,但我需要理解这一点。提前谢谢。
附言:这是用户模型。
struct User: Encodable {
let name : String?
let email : String?
let password : String?
}发布于 2018-10-22 16:16:18
首先,反斜杠是虚拟的。框架添加它们是为了能够在文字字符串中使用print双引号。
其次,dataTask返回序列化的JSON Data,因此要从必须调用jsonObject(with的数据中获取字典或数组。
let object = try JSONSerialization.jsonObject(with: data)
print(object)https://stackoverflow.com/questions/52924375
复制相似问题