将JSON DATA转换为Swift 3中的可用变量

时间:2017-07-07 18:40:11

标签: json swift3 xcode8

我目前有代码可以获取我提供的json数据并解析它但是我将所有内容都包含在for循环中并且我不知道如何将其取出。

JSON数据:

[
{
"id": 1,
"displayName": "Jacob Blacksten",
"department": "DF",
"mamager": "San",
"office": "NYC",
"util": 2
}
]

工作代码:

do {
   let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)

      guard let array = json as? [Any] else {return}

      for user in array {
          guard let userDict = user as? [String: Any] else {return}
          guard let id = userDict["id"] as? Int else { return }
          guard let name = userDict["displayName"] as? String else { return}
          guard let department = userDict["department"] as? String else {return}
          guard let manager = userDict["mamager"] as? String else {return}
          guard let office = userDict["office"] as? String else {return}
          guard let util = userDict["util"] as? Int else {return}

                print(id)
                print(name)
                print(department)
                print(manager)
                print(office)
                print(util)
            }

        } catch{
           print(error)
        }

你会注意到一切都在for循环中,创建了一个包含所有“用户”的数组。但是我只有一个用户,我希望能够拉出说“id”并将其用作变量,以便稍后在我的应用程序中的标签中打印出来。我希望这是有道理的。我基本上只是想操纵这个JSON数据,以便我可以使用它并在我的应用程序中的标签中打印它们。

1 个答案:

答案 0 :(得分:1)

如果您尝试在其他地方使用变量,则只需将它们保存到循环范围之外的某些位置即可。我建议创建一个User类并将值从json保存到User的实例。

// User.swift
class User {
    // Identifier
    let id: Int

    // Instance variables
    var name: String?
    var department: String?
    var manager: String?
    var office: String?
    var util: Int?

    init(withId id: Int) {
        self.id = id
    }
}

然后,你可以把你的循环变成这样的东西。

var user: User?

do {
    let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)

    guard let array = json as? [Any],
      let userDict = array[0] as? [String: Any],
      let id = userDict["id"] as? Int,
      let name = userDict["displayName"] as? String,
      let department = userDict["department"] as? String,
      let manager = userDict["manager"] as? String,
      let office = userDict["office"] as? String,
      let util = userDict["util"] as? Int else { 
        return
    }

    user = User(withId: id)

    user.name = name
    user.department = department
    user.manager = manager
    user.office = office
    user.util = util

} catch{
    print(error)
}

 // Here, the user variable has all the updated info
 userIdLabel?.text = "\(user?.id)"

注意:这一切都在浏览器中,没有测试