【问题标题】:retrieving JSON data and then parsing it (need some help)检索 JSON 数据然后解析它(需要一些帮助)
【发布时间】:2019-10-23 23:37:08
【问题描述】:

您好,我正在尝试获取更多关于如何从网站获取 JSON 代码然后对其进行解析的经验。 (见下面的代码)这有效,但我从苹果那里了解到这是一种“旧的,2017 年”的方式来做到这一点。而且我的字典有些问题,

问题1。如何在不使用任何其他 3rd 方方法或软件的情况下改进以下代码。

如何摆脱 Optional 语句,我只想打印 print(jsondata["title"]) 的值

我希望你能给我指明正确的方向。

谢谢罗恩

查看代码

'''

//: Playground - noun: a place where people can play
// put in some requirements to yse the playground
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

import Foundation
import UIKit

//just a check if I get some output in a variable and to see if the playground is working
var str = "this is a test to see if there is output"

// retrieve the data from a website and put it into an object called jsondata; print the size of jsondata in bytes and put it into a variable called data; put number of elements in jsondata into jsonelements

let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")
URLSession.shared.dataTask(with:url!, completionHandler: {(datasize, response, error) in
    guard let data = datasize, error == nil else { return }

do {
    let jsondata = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]

    //print the dictionary
    print(jsondata)

    // how many elements in the dictionary
    let jsonelements = jsondata.count
    print(jsonelements)

    // Iterate through the dictionary and print the value per key
    for (key,value) in jsondata {
        print("\(key) = \(value)")
    }

    // get the values out of the dictionry
    print(" ")
    print(jsondata["title"])
    print(jsondata["userID"])
    print(jsondata["id"])
    print(jsondata["completed"])

} catch let error as NSError {
    print(error)
}

}).resume()

'''

    // get the values out of the dictionry
    print(" ")
    print(jsondata["title"])
    print(jsondata["userID"])
    print(jsondata["id"])
    print(jsondata["completed"])

在这里我得到一个警告“从'Any?'中隐式强制的表达式到任何

为什么我会收到警告? 以及如何在没有警告的情况下仅打印 print(jsondata["title"] 。 我认为我的做法是正确的

【问题讨论】:

    标签: json swift api swift4.2


    【解决方案1】:

    要消除警告并打印出没有可选值的值,请使用 if let 如下所示。

    if let title = jsondata["title"] {
       print(title)
    }
    

    你也可以使用 guard let 来做到这一点

    guard let title = jsondata["title"] else { return }
    print(title)
    

    如果你是 100% 的返回类型并且它不会是 nil 使用 guard let 或

    print(jsondata["title"] as! String)
    

    但是,不推荐使用上面的示例,因为您通常不想强制 unwrap(!)

    关于警告和另一个例子 -> https://stackoverflow.com/a/40691455/9578009

    【讨论】:

      【解决方案2】:

      这样做的标准方法是声明一个类型并如下使用它,

      // MARK: - Response
      struct Response: Codable {
          let userID, id: Int
          let title: String
          let completed: Bool
      
          enum CodingKeys: String, CodingKey {
              case userID = "userId"
              case id, title, completed
          }
      }
      
      URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
          guard let data = data else { return }
      
          do {
              let response = try JSONDecoder().decode(Response.self, from: data)
              print(response.id)
              print(response.userID)
              print(response.title)
              print(response.completed)
          } catch {
              print(error)
          }
      
      }).resume()
      

      【讨论】:

        【解决方案3】:

        问题1。如何在不使用任何其他 3rd 方方法或软件的情况下改进以下代码。

        使用Decodable,它将数据直接解码为结构。没有可选项,没有Any

        //: Playground - noun: a place where people can play
        // put in some requirements to yse the playground
        import PlaygroundSupport
        PlaygroundPage.current.needsIndefiniteExecution = true
        
        import Foundation
        import UIKit
        
        struct ToDo : Decodable {
        
            let userId, id : Int
            let title : String
            let completed : Bool
        }
        
        let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")!
        URLSession.shared.dataTask(with:url) { data, _, error in
            guard let data = data else { print(error!); return }
        
            do {
                let todo = try JSONDecoder().decode(ToDo.self, from: data)
        
                // get the values out of the struct
                print(" ")
                print(todo.title)
                print(todo.userId)
                print(todo.id)
                print(todo.completed)
        
            } catch {
                print(error)
            }
        }.resume()
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-03-30
          • 1970-01-01
          • 2016-07-14
          • 2021-01-02
          • 2018-12-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多