如何使用循环从JsonResult获取元素(Swift 3)

时间:2017-02-20 06:42:02

标签: swift3

let jsonResult = try JSONSerialization.jsonObject(with: jsonData!, options: .mutableContainers) as! NSDictionary

当调试器出现在上面一行时,在调试控制台中有 - >

jsonResult =(NSDictionary) 2 key/value pairs
>[0] = “CompanyList” : 140 elements
>[1] = “StatusTable” : 1 element

jsonResult包含2个数组

现在我想使用Loop遍历CompanyList 像

let arr_CompanyList = [CompanyList]()
for dictionary in json as! [[CompanyList]]
{
  //arr_CompanyList.append(dictionary)            
}

但是给出了错误

这是CompanyList Class

public class CompanyList {
    public var companyAlt_Key : Int?
    public var company_Name : String?
    public var tableName : String?
}

我该怎么办?

1 个答案:

答案 0 :(得分:1)

您无法将JSON数组响应直接转换为您的Class对象数组,您需要从JSON响应中创建自定义类对象。另外,不要在swift中使用NSDictionary使用原生类型Dictionary

if let jsonResult = (try? JSONSerialization.jsonObject(with: jsonData!, options: [])) as? [String:Any] {
    if let companyList = jsonResult["CompanyList"] as? [[String:Any]] {
        //Now loop through the companyList array
        let arr_CompanyList = companyList.flatMap(CompanyList.init)
        //To get array of companyname
        let companyNames = companyList.flatMap { $0["Company_Name"] as? String }
        print(companyNames)
    }
}

现在只需添加一个init CompanyList类,就像这样。

public class CompanyList {
    public var companyAlt_Key : Int?
    public var company_Name : String?
    public var tableName : String?


    init?(dictionary: [String:Any]) {
        guard let companyAltKey = dictionary["CompanyAlt_Key"] as? Int, 
           let companyName = dictionary["Company_Name"] as? String,
           let tableName = dictionary["TableName"] as? String else {
               return nil
        }
        self.companyAlt_Key = companyAltKey
        self.company_Name = companyName
        self.tableName = tableName
    }
}

注意:init?方法dictionary内,您需要根据您的类属性访问包含值的密钥。