【问题标题】:Parsing JSON response in Swift 3在 Swift 3 中解析 JSON 响应
【发布时间】:2016-11-07 16:24:35
【问题描述】:

我有一个 API 端点,它以以下格式返回 JSON:

[
  {
    "id": "1",
    "name": "John"
  },
  {
    "id": "2",
    "name": "Jane"
  },
  {
    "id": "3",
    "name": "Nick"
  }
]

我试图在 Swift 3 中解析它,但我只能找到解析 JSON 格式的示例:

{
"blogs": [
    {
        "needspassword": true,
        "id": 73,
        "url": "http://remote.bloxus.com/",
        "name": "Bloxus test"
    },
    {
        "needspassword": false,
        "id": 74,
        "url": "http://flickrtest1.userland.com/",
        "name": "Manila Test"
    }
],
"stat": "ok"
}

,比我的要高出一个层次。

所以,我见过的例子只是简单地解析他们的数据,比如jsonResponse["blogs"],我不能这样做,因为我的格式不同。

我怎样才能解析我得到的格式,或者我怎样才能返回一个更容易解析的格式?

任何建议表示赞赏,谢谢!

【问题讨论】:

    标签: json swift http


    【解决方案1】:

    您可以执行以下操作:

        let data = // Data received from WS
        do {
            let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) as? [[String : String]]
            //json is now an array from dictionary matching your model
        }
        catch {
           //handle error
        }
    

    【讨论】:

      【解决方案2】:

      这将在放入网络调用时对其进行解析。

              do {
                  let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions()) as! [[String : AnyObject]]
                  let firstPerson = json[0]
                  print(firstPerson)
                  let id = firstPerson["id"] as! String
                  print(id)
                  let name = firstPerson["name"] as! String
                  print(name)
              } catch {
                  //handle error
              }
      

      另外,我倾向于反对向第三方库提供建议,但 SwiftyJSON 是我提出的一个例外。如果您想尝试一下,请将其添加到您的 pod 文件中:

      pod SwiftyJSON', '3.0.0'

      文档:https://github.com/SwiftyJSON/SwiftyJSON

      编辑 - 回复评论:

      替换线:

      if let id = firstPerson["id"] as? String {
          print(id)
      }
      

      替换线(如果您需要保留该值):

      var thisId: String?
      if let id = firstPerson["id"] as? String {
          thisId = id
      }
      print(thisId ?? "")
      

      【讨论】:

      • 好吧,我迟到了,但我想知道一些事情。在这一行:let id = firstPerson["id"] as! String。如果firstPerson["id"]的值为nil,会不会导致崩溃?
      • 是的,替换行将是我将在编辑中添加的内容
      【解决方案3】:

      我真的不知道 swift 但可能有相当于 ajax json 编码(服务器端你 json_encode 你的数组和客户端你 json_decode 响应)

      这个想法是使用相同的格式化程序来编码和解码数据

      【讨论】:

      • 永远不要回答以“我真的不知道_____”开头的语言特定问题。把时间花在堆栈溢出上,看看适用于你的知识库的问题。
      猜你喜欢
      • 2017-02-17
      • 1970-01-01
      • 1970-01-01
      • 2021-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-14
      • 1970-01-01
      相关资源
      最近更新 更多