在tableview中填充JSON

时间:2016-06-20 10:35:46

标签: json swift

所以我试图使用下面的json代码填充多个tableviews:

{   "company":[
    {   "company_id":"0",
        "name": "Company Name",
        "phone_number":"0123978978",
        "website":"http:\/\/www.Company.co.uk\/",
        "email":"Company@hotmail.co.uk",
        "address":"123 Alm Street...",
        "employees":[
            {
                "company_id": "0",
                "name":"Steve",
                "age":"25",
                "description":"desc"},
            {
                "company_id": "0",
                "name":"Paul",
                "age":"35",
                "description":"desc"}]

        }
    ]
}

下面是获取json并将其格式化为我可以使用的东西的模型

class Company: NSObject {
var name: String
var phoneNumber: String
var website: String
var email: String
var address: String
var employees: [Employee]

override init() {

}

init(name: String, phoneNumber: String, website: String, email: String, address: String, employees: [Employee]) {
    self.name = name
    self.phoneNumber = phoneNumber
    self.website = website
    self.email = email
    self.address = address
    self.employees = employees
}
}

class Employee : NSObject {
var name:String
var age:Int
var information:String

override init() {

}

init(name: String, age: Int, information: String) {
    self.name = name
    self.age = age
    self.information = information
}
}

func getJSON(completion: (array: [Company])->()) {

var companyArray = [Company]()

let requestURL: NSURL = NSURL(string: urlString)!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
let session = NSURLSession.sharedSession()

let task = session.dataTaskWithRequest(urlRequest) {
    data, response, error -> Void in

    let httpResponse = response as! NSHTTPURLResponse
    let statusCode = httpResponse.statusCode
    if (statusCode == 200) {
        print("Everything is fine, file downloaded successfully.")

        do{

            let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)

            if let companies = json["companies"] as? NSArray {

                for companyDict in companies {

                    let company = Company()
                    let employee = Employee()
                    var employeeArray = [Employee]()

                    if let name = companyDict["name"] as? String,
                        let phoneNumber = companyDict["phone_number"] as? String,
                        let website = companyDict["website"] as? String,
                        let email = companyDict["email"] as? String,
                        let address = companyDict["address"] as? String {

                            company.name = name
                            company.phoneNumber = phoneNumber
                            company.website = website
                            company.email = email
                            company.address = address
                        }
                    if let employees = companyDict["employees"] as? NSArray {
                        for employeesDict in employees {
                            if let name = employeesDict["name"] as? String,
                                let age = employeesDict["age"] as? Int,
                                let information = employeesDict["information"] as? String {
                                var employeeArray = [Employee]()
                                let employee = Employee()

                                employee.name = name
                                employee.information = information
                                employee.age = age
                                employeeArray.append(employee)
                                company.employees = employeeArray
                            }
                        }
                    }
                    companyArray.append(company)

                }
                dispatch_async(dispatch_get_main_queue()) {
                    completion(array: companyArray)
                }

            }

        } catch {
            print("Error with Json: \(error)")
        }

    }

}

task.resume()
}

这是问题所在的地方,我可以填写我的第一个tableview罚款。每个单元格都显示数据正常。当我尝试根据第一个tableview中选择的单元格填充第二个tableview时,会出现问题。

let selectedCompany:Company?

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.selectedCompany!.employees!.count //ignore force unwrap
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let employee = self.selectedCompany!.employees![indexPath.row] //ignore force unwrap

    cell.employeeName.text = employee.name


    return cell
}

let employee = self.selectedCompany!.employees![indexPath.row]显示编译器错误type has no subscript members。我想我知道为什么 - 我需要将第二个表视图填充为数组。目前,Employee不是一个数组。我已经尝试了几种不同的方法来使它成为一个数组,但我似乎无法做到这一点。我试过的通常会返回nil并且应用程序崩溃或者我遇到编译器错误

1 个答案:

答案 0 :(得分:1)

您必须在employees中将Company声明为数组

var employees = [Employee]() 

以及初始化程序

init(name ... , employees: [Employee]) {

和 - 非常非常重要 - 你必须在重复循环中创建Employee实例,否则你有employees.count次相同的对象(由于参考语义的原因)类)

   ...
   for employeesDict in employees {
       if let name = employeesDict["name"] as? String,
          let age = employeesDict["age"] as? Int,
          let information = employeesDict["information"] as? String {
             let employee = Employee(name:name, age:age, information:information)
             employeeArray.append(employee)
          }
       }
   } 
   company.employees = employeeArray
   ...

无论如何你必须使用初始化器。并且你必须在重复循环之后分配数组。