如何从字典swift3中获取价值

时间:2016-12-07 06:00:37

标签: json dictionary swift3

我有Dictionary这样的,我得到了“OutputResult”的价值,但我如何得到“company_id”,“部门”等的价值。

 if let convertedJsonIntoDict = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary 


 let firstNameValue = convertedJsonIntoDict["OutputResult"] as? String
                print("OutputResult is :\(firstNameValue!)")

{
OutputResult = true;
msg =     {
    "company_id" = 1;
    "department_id" = 6;
    email = "abc@gmail.com";
    "employee_code" = 014;
    "employee_id" = 131;
    "employee_name" = "abc dsc";
    "have_power" = 0;
    ip = "";
    "is_deleted" = 0;
    lastactivity = "";
    status = 1;
};
}

1 个答案:

答案 0 :(得分:1)

您需要使用Swift原生Dictionary代替NSDictionary,它可以让您轻松访问Dictionary。从您的回复看,OutputResult包含Boolean值,您的company_iddepartment_id位于另一个词典msg内,所以您尝试下面的内容。< / p>

if let convertedJsonIntoDict = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any]  {
    if let msg = convertedJsonIntoDict["msg"] as? [String: Any], let company_id = msg["company_id"] as? Int,
       let department_id = msg["department_id"] as? Int {
           //You can same way access other details of employee, email, etc..
           print(company_id)
           print(department_id)
    }
}