iOS 创建 JSON 文件作为样本数据来测试网络和解析逻辑

标签 ios json

我正在处理一个处理向服务器发送请求并获取 JSON 响应的项目​​。有没有办法创建一个离线 JSON 文件作为示例数据,以便应用程序从示例数据文件中读取而不是发出真正的网络请求?我想在编写 network 调用之前测试 JSON parsingmapping

例如,我们如何从这个 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/

相关文章:

ios - 是否有可能在给定一系列约束的情况下获得计算框架?

mysql - 如何以 json 格式导出所有具有从所述日期到所述日期的对话表的数据库

javascript - 如何从键/值 JSON 对象中提取键?

ios - 什么是自动释放范围?

ios - 当 UITableViewCell 调整大小时重新排列单元格 subview

ios - UITextField 边框在左侧和底部不同

java - 在 Java 中将 BigDecimal 字段作为 JSON 字符串值返回

java - Spring MVC : strange @ResponseBody behavior

java - 我将如何使用java处理 "sub strings?"JSON文件?

ios - 为 qmake TARGET 变量使用带空格的名称