Swift3 如何使用循环(Swift 3)从JsonResult获取元素
当调试器出现在第行上方时,在调试控制台中有->Swift3 如何使用循环(Swift 3)从JsonResult获取元素,swift3,Swift3,当调试器出现在第行上方时,在调试控制台中有-> let jsonResult = try JSONSerialization.jsonObject(with: jsonData!, options: .mutableContainers) as! NSDictionary jsonResult包含2个数组 现在我想使用循环遍历CompanyList 像 但这是错误的 这是公司列表类 let arr_CompanyList = [CompanyList]() for dictionary in
let jsonResult = try JSONSerialization.jsonObject(with: jsonData!, options: .mutableContainers) as! NSDictionary
jsonResult包含2个数组
现在我想使用循环遍历CompanyList
像
但这是错误的
这是公司列表类
let arr_CompanyList = [CompanyList]()
for dictionary in json as! [[CompanyList]]
{
//arr_CompanyList.append(dictionary)
}
我该怎么做?您不能将JSON数组响应直接转换为类对象数组,您需要从JSON响应创建自定义类对象。也可以使用本机类型字典,而不是在swift中使用NSDictionary
现在只需像这样在CompanyList类中添加一个init
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内部?方法,您需要根据类属性访问包含值的密钥。@DilipJangid从何处获取此Jsonresult,如果它已经是CompanyList的数组,那么您需要什么。@DilipJangid如果您的数组已经是CompanyList的类型,那么您需要如何处理它,要将其转换为JSON响应吗?@DilipJangid为此,您需要向我显示此语句的控制台日志printjsonResult[CompanyList]添加此print语句并向我显示其控制台日志,注意不要强制转换响应,只需像我的一样添加打印。@DilipJangid那么您的数组是字典数组而不是公司列表对象数组。@DilipJangid欢迎伴侣:
public class CompanyList {
public var companyAlt_Key : Int?
public var company_Name : String?
public var tableName : String?
}
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)
}
}
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
}
}