如何从字典swift3
问题描述:
获得价值我有Dictionary
这样,我得到“OutputResult”的价值,但我怎么弄“的company_id”的价值,“部门”等。如何从字典swift3
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 = "[email protected]";
"employee_code" = 014;
"employee_id" = 131;
"employee_name" = "abc dsc";
"have_power" = 0;
ip = "";
"is_deleted" = 0;
lastactivity = "";
status = 1;
};
}
答
您需要使用快速原生Dictionary
而不是NSDictionary
,它会让您从Dictionary
轻松访问。从您的回应看起来像OutputResult
包含Boolean
值,也是你的company_id
和department_id
是在另一个字典msg
所以你尝试下面的东西。
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)
}
}
感谢您rply但错误在这行 **如果让味精= convertedJsonIntoDict [ “味精”],让COMPANY_ID =味精[ “COMPANY_ID”]作为? Int, let department_id = msg [“department_id”] as? Int ** 其显示类型“任何”没有下标成员 – johnyDiOS
@johny忘记了添加'as? [字符串:任何]'检查编辑的答案。 –
其工作我得到它,并感谢您的教学 – johnyDiOS