我正在处理一个处理向服务器发送请求并获取 JSON 响应的项目。有没有办法创建一个离线 JSON 文件作为示例数据,以便应用程序从示例数据文件中读取而不是发出真正的网络请求?我想在编写 network
调用之前测试 JSON parsing
和 mapping
例如,我们如何从这个 JSON 生成一个 JSON 文件?
{
"by" : "dhouston",
"descendants" : 71,
"id" : 8863,
"kids" : [ 8952, 9224, 8917, 8884, 8887, 8943, 8869, 8958, 9005, 9671, 9067, 8940, 8908, 9055, 8865, 8881, 8872, 8873, 8955, 10403, 8903, 8928, 9125, 8998, 8901, 8902, 8907, 8894, 8878, 8980, 8870, 8934, 8876 ],
"score" : 111,
"time" : 1175714200,
"title" : "My YC app: Dropbox - Throw away your USB drive",
"type" : "story",
"url" : "http://www.getdropbox.com/u/2/screencast.html"
}
最佳答案
使用它来序列化、发布并返回一个 json:
let json = ["by":"dhouston","descendants":"71"]
do {
let jsonData = try JSONSerialization.data(withJSONObject: json, options: [])
let url = NSURL(string: "your url")!
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
request.httpBody = jsonData
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
let task = URLSession.shared.dataTask(with: request as URLRequest){ data,response,error in
if error != nil{
print(error!.localizedDescription)
return
}
let header = response as! HTTPURLResponse
print(header.allHeaderFields)
do {
let responseObject = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String: String] // your json response for example [String: String], depends on what you get as a response
print(responseObject)
// do something
} catch let jsonError {
print(jsonError)
print(String(data: data!, encoding: String.Encoding.utf8)!)
}
}
task.resume()
} catch {
print(error)
}
如果你只是想序列化使用:
let json = ["by":"dhouston","descendants":"71"]
do {
let jsonData = try JSONSerialization.data(withJSONObject: json, options: [])
} catch {
print(error)
}
关于iOS 创建 JSON 文件作为样本数据来测试网络和解析逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43395773/