【问题标题】:Xcode playground - Swift 4 not receiving the JSON dataXcode 游乐场 - Swift 4 未接收 JSON 数据
【发布时间】:2018-08-06 06:14:33
【问题描述】:

您好,我在 Xcode 游乐场工作,并尝试使用 URLSession 的 API http-get 请求和来自 jsonplaceholder 网站的虚拟数据。

见下面的代码。该代码没有返回错误,但我期待“usableData”中的数据并打印它。数据是:

{ URL: http://jsonplaceholder.typicode.com/users/1 } { 状态代码: 200, Headers {\n "Access-Control-Allow-Credentials" = (\n true\n );\n "CF-Cache-Status" = (\ n HIT\n );\n "CF-RAY" = (\n "445f3d1003761d3e-MEL"\n );\n "缓存控制" = (\n "public, max-age=14400"\n ); \n Connection = (\n "keep-alive"\n );\n "Content-Encoding" = (\n gzip\n );\n "Content-Type" = (\n "application/json; charset= utf-8"\n );\n 日期 = (\n "星期一,2018 年 8 月 6 日 05:52:38 GMT"\n );\n Etag = (\n "W/\"1fd-+2Y3G3w049iSZtw5t1mzSnunngE\" "\n );\n Expires = (\n "Mon, 06 Aug 2018 09:52:38 GMT"\n );\n Pragma = (\n "no-cache"\n );\n Server = ( \n cloudflare\n );\n "Transfer-Encoding" = (\n Identity\n );\n Vary = (\n "Origin, Accept-Encoding"\n );\n Via = (\n "1.1我……”

我期待一些 JSON 格式的数据:

{
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
        "street": "Kulas Light",
        "suite": "Apt. 556",
        "city": "Gwenborough",
        "zipcode": "92998-3874",
        "geo": {
            "lat": "-37.3159",
            "lng": "81.1496"
        }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
        "name": "Romaguera-Crona",
        "catchPhrase": "Multi-layered client-server neural-net",
        "bs": "harness real-time e-markets"
    }
} 

在这个阶段,我只对获取数据感兴趣,而不是对其进行解析。

我做错了什么?欢迎任何帮助。谢谢。

---- 开始代码 ---------------

import PlaygroundSupport
import Foundation
PlaygroundPage.current.needsIndefiniteExecution = true

let urlString = URL(string:"http://jsonplaceholder.typicode.com/users/1")

if let url = urlString {
    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
        if error != nil {              
            print()
        } else {
            if let usableData = data {
                print(usableData) //JSONSerialization
            }
        }
    }
    task.resume()
}

【问题讨论】:

  • 代码应该可以工作并打印"509 bytes"。并且可选绑定if let usableData 是多余的。如果没有错误data可以安全解包。
  • 正确,我得到了 509 个字节。我将尝试转换为可读的 JSON。

标签: swift swift4 swift-playground


【解决方案1】:

您的代码很好。如果要查看打印为字符串的 JSON 数据,则需要将字节从 data 转换为字符串:

if let usableData = data {
    let str = String(bytes: data, encoding: .utf8)
    print("\(String(describing: str))") // just for debug output
}

请注意,这不是解析所必需的,您可以按照以下方式进行操作

struct User: Codable {
    let id: Int
    let name, username, email: String
    let address: Address
    let phone, website: String
    let company: Company
}

struct Address: Codable {
    let street, suite, city, zipcode: String
    let geo: Geo
}

struct Geo: Codable {
    let lat, lng: String
}

struct Company: Codable {
    let name, catchPhrase, bs: String
}

if let usableData = data {
    try {
       let user = try JSONDecoder().decode(User.self, from: data)
    } catch {
       print("\(error)"
    }
}

为此

【讨论】:

  • 请不要建议像print("\(String(describing: str))")这样的重言式语法。 JSON 数据中的字符串永远不能是nilprint(str!) 就足够了。
  • 好吧,代码中没有任何内容(据我所知,服务器上也没有)真正确保涉及 JSON。因此,我们不知道 data 中有哪些字节,因此实际上转换为 String 可能会失败,这就是为什么我不愿意向初学者推荐强制展开。
  • http://jsonplaceholder.typicode.com/users/1粘贴到浏览器中查看。它 json。但我更关心的是打印带有字符串插值的 string,它是由带有 describing 初始化程序的 string 创建的。除了 OP 写道 在这个阶段我只对获取数据而不是解析它感兴趣
  • Vadian 是正确的。这给出了结果.. if let usableData = data { let str = String(bytes: data!, encoding: .utf8) print("(str!))") // 仅用于调试输出
  • 感谢您的帮助以及我在我的 xcode 操场上的尝试和错误。现在新的进化将被解析。
【解决方案2】:

您必须使用 Foundation 类 NSJSONSerialization 将您从 api 获得的 json 数据转换为对象。所以你可以使用下面的行:

let usableData = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary
print(usableData)

【讨论】:

  • 问题是关于 Swift 4,我们有 CodableJSONDecoderNSJSONSerialization 应该避免。
  • 好的,你能在我的代码中给我一个例子吗?我认为 coddle 更多地与获取数据后的解析有关。我还没有。 @Gereon请给我一个使用我的代码的例子。谢谢
  • 没错,Codable 用于将 JSON 数据解析为实际的 Swift 对象。我已经用一个例子更新了我的答案。
  • @RvE 你怎么能接受这个答案?它甚至不能在 Swift 4 中编译
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多