【问题标题】:Swift 2 parsing and reading JSONSwift 2 解析和读取 JSON
【发布时间】:2016-03-08 15:48:10
【问题描述】:

我是 Swift 2.0 的新手,但我有 OOP 语言方面的经验。我试图通过 JSON API 在标签中显示城市的名称。但我不断收到错误“EXC_BAD_INSTRUCTION”和“Unwrapping nil”错误。我认为问题可能出在 URL 中。因为我尝试过使用另一个 API,radnomuser.me/api,所以我得到了没有错误的结果。有人可以引导我解决问题,因为我在互联网上得到了很多答案,而且所有答案都不一样。如果您不理解我的问题,请随时提问,因为我认为这是至关重要的部分。 谢谢!

@IBOutlet weak var viaSegueTextView: UITextView!{

var viaSegue = ""

override func viewDidLoad() {
    super.viewDidLoad()

    getWeatherData()



}

//////////////////////////////////////////////////////////////////////////
func getWeatherData {
     let endpoint = NSURL(string: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=44db6a862fba0b067b1930da0d769e98")
    let data = NSData(contentsOfURL: endpoint!)

    do {
      if let json: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {
             if let name = json["name"] as? String
            {

                    viaSegueLabel.text = "\(name)"

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

【问题讨论】:

  • 解析和阅读都很好。您的viaSegueLabel 为零。我在 Playground 中尝试了您的下载/解析 sn-p,它解析得很好。也为下一次 - 不要永远发布您的应用程序 ID、登录名等...
  • 感谢您的提示,它只是测试应用程序,只是读取 JSON 并显示数据,但我明白您的意思。我还是不明白。我知道我有 nil,这意味着我没有从 JSON 中获得价值。出于某种原因,它在“if”之前停止,viaSequeLabel 为 nil,因为它没有解析它,或者因为 URL 错误或其他原因?感谢您的回复。
  • 这不是问题,但JSONObjectWithData 不返回可选,因此可选绑定是无用的。写let json = try NSJSONSerialization.JSONObjectWithData(jsonData, options: []) as! [String:AnyObject],如果发生错误会执行catch块
  • @vadian 你能推荐我用什么吗?

标签: ios json swift2


【解决方案1】:
import Foundation

func getWeatherData() {
    guard let endpoint = NSURL(string: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=44db6a862fba0b067b1930da0d769e98"),
        let data = NSData(contentsOfURL: endpoint) else { return }

    do {
        if let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {
            if let name = json["name"] as? String {
                print(name) // London
            }
        }
    } catch let error as NSError{
        print("\(error)")
    }
}
getWeatherData() // prints
// London

【讨论】:

    【解决方案2】:
    • 首先,您必须在 InterfaceBuilder 中链接您的 IBOutlet。这可能是您得到 unwrapping nil 错误的第一个点。
    • 第二点,viewDidLoad 是视图控制器上的一个方法,我不明白为什么你的括号在 UITextView 之后。
    • 第三,您的代码中没有声明viaSegueLabel。
    • 第四,尽量不要强制解开这么多的选项(使用!),而是使用 if let。
    • 对于第一次迭代,我会像这样更改 getWeatherData 方法:

      func getWeatherData() {
          let endpoint = NSURL(string: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=44db6a862fba0b067b1930da0d769e98")
          if let endpoint = endpoint, data = NSData(contentsOfURL: endpoint) {
              do {
                  if let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {
                      if let name = json["name"] as? String
                      {
                          print(name)
                      }
                  }
              } catch let error as NSError{
                  print("\(error)")
              }
          }
      }
      

    【讨论】:

    • 对不起,变量声明错误,viaSegueLabel 是一个出口,它被声明了,但我写错了。我试过不强迫它,但 Xcode 强迫我这样做。感谢您的回答。
    【解决方案3】:

    SWIFT 3

    func WeatherData() { 守卫让端点= NSURL(字符串:“http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=44db6a862fba0b067b1930da0d769e98”), let data = NSData(contentsOf: endpoint as URL) else { return }

        do {
            if let json = try JSONSerialization.jsonObject(with: data as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary {
                if let weather = json["weather"] as? NSDictionary {
                    print(weather) // London
                }
            }
        } catch let error as NSError{
            print("\(error)")
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多