使用Swift 2.0解析并跳转到JSON文件中的下一个块

wj8zmpe1  于 2023-06-04  发布在  Swift
关注(0)|答案(1)|浏览(213)

我目前正在学习如何在Swift 2.0中获取和解析JSON文件。

    • 这是我朋友提供的示例JSON文件**
{
  "name": "Busitevent",
  "count": 398,
  "frequency": "Every 30 mins",
  "version": 93,
  "newdata": true,
  "lastrunstatus": "success",
  "thisversionstatus": "success",
  "nextrun": "Wed Feb 10 2016 02:43:20 GMT+0000 (UTC)",
  "thisversionrun": "Wed Feb 10 2016 02:13:19 GMT+0000 (UTC)",
  "results": {
    "collection1": [
      {
        "eventTitles": {
          "href": "https://events.ucsc.edu/event/3338",
          "text": "32nd Annual Martin Luther King Jr. Convocation featuring Alicia Garza"
        },
        "eventDates": "",
        "eventDescription": "",
        "index": 1,
        "url": "https://events.ucsc.edu/"
      }
}

我正在尝试模式匹配“collection1”,以便将其转换为对象

    • 这是我到目前为止得到的(用假的URL替换)**
let url = NSURL(string: "www.jsonsourcefile.com")
    let request = NSURLRequest(URL: url!)

    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
        //print(NSString(data: data!, encoding: NSUTF8StringEncoding))
        var names = [String]()

        do {
            let json : NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! NSDictionary

            if let collection1 : NSArray = json["collection1"] as? NSArray{
                print("you got it")
                        //names.append(collection1)
    }

        } catch {
            print("error serializing JSON: \(error)")
        }

        print(names) // ["Bloxus test", "Manila Test"]

    }

所以我面临的主要问题是collection1没有被我的if语句匹配,我不知道为什么。

n3h0vuf2

n3h0vuf21#

在尝试检索collections1数组之前,必须首先获取results字典。下面提供的代码将给予您很好地理解如何在没有任何第三方解析器的情况下解析JSON。
JSON示例:(因为问题没有有效的JSON)

{
    "employees":[{
            "firstName":"John",
            "lastName":"Doe"
        },
        {
            "firstName":"Anna",
            "lastName":"Smith"
        },
        {
            "firstName":"Peter",
            "lastName":"Jones"
    }]
}

在上面的JSON中,您必须注意以下内容:

  • 它是一本对象词典
  • employees对象是字典数组

要获取firstName的值,必须执行嵌套的if let块来获取数据。

var jsonString = "{\"employees\":[{\"firstName\":\"John\", \"lastName\":\"Doe\"},{\"firstName\":\"Anna\", \"lastName\":\"Smith\"},{\"firstName\":\"Peter\", \"lastName\":\"Jones\"}]}"

do {
    let data = jsonString.dataUsingEncoding(NSUTF8StringEncoding)
    let json: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! NSDictionary

    if let employees = json["employees"] as? [NSDictionary] {
        for employee in employees {
            if let firstName = employee["firstName"] {
                print("First name ===> \(firstName)")
            }
        }
    }
    else {
        print("failure")
    }
}
catch let error as NSError {
    print("Error while parsing data ===> \(error)")
}

**注意:**如果需要解析更大的JSON,嵌套的if let s的复杂度会更高。有第三方Swift JSON解析器(如SwiftyJSON)可以简化您访问对象的方式。SwiftyJSON使用与@kye提到的语法类似的语法。

相关问题