将JSON字符串解析为Model Object类型Array

时间:2017-02-18 11:18:48

标签: swift3

我通过以下方法获得API加密数据

URLSession.shared.dataTask(with: url!) 

将数据转换为JSON,但仍然是加密的

var json = try(JSONSerialization.jsonObject(with: data!, options: .allowFragments))

将其转换为字符串

let arr:String = json as! String 

解密它

let jsonText = arr.fromBase64()//extension method, given end of question

现在它在Json Formate中如下(这只是1条记录,Json字符串中有超过1条记录)

{
  "CompanyAlt_Key": 1,
  "Company_Name": "XYZ LTD",
  "TableName": "CompanyList"
},

我有一个相同类型的模型

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

这里是fromBase64方法

func fromBase64() -> String {
    let data = NSData.init(base64Encoded: self, options: []) ?? NSData()
    return String(data: data as Data, encoding: String.Encoding.utf8) ?? ""
}

我遇到了将Json String转换为CompanyList类

类型的数组的问题

帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

您需要先将jsonString转换为数据:

let jsonData = jsonString.data(using: .utf8)!

将数据转换为数组

let array = JSONSerialization.jsonObject(with: jsonData, options: nil) as? [[String: Any]]

然后遍历数组...

let companies = array?.map {
    return CompanyList(dictionary: $0)
}

为您的init实施CompanyList方法,为您的回复中的每条记录传入字典...

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

    init(dictionary: [String: Any]) {        
        companyAlt_Key = dictionary["companyAlt_Key"] as? Int
        company_Name = dictionary["company_Name"] as? String
        tableName = dictionary["tableName"] as? String
    }
}

您也可以使用它来验证数据。如果您班级中的字段是非可选字段,则可以使用可选的init,如下所示......

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

    init?(dictionary: [String: Any]) {        
        guard let companyAlt_Key = dictionary["companyAlt_Key"] as? Int,
        let company_Name = dictionary["company_Name"] as? String,
        let tableName = dictionary["tableName"] as? String else {
            return nil 
        }

        self.companyAlt_Key = companyAlt_Key
        self.company_Name = company_Name
        self.tableName = tableName
    }
}

如果您使用的是可选的初始化,请使用flatMap确保您的阵列中没有任何可选元素...

let companies = array?.flatMap {
    return CompanyList(dictionary: $0)
}