我对swift非常新,我曾经在目标C中编码,但是现在我在Swift开发时面临很多问题。现在我在项目中导入了json文件
let file = Bundle.main.url(forResource: "test", withExtension: "json")
do {
let data = try Data(contentsOf: file!)
//let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
let json:NSArray = try (JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.mutableContainers) as? NSArray)!
print(json[0])
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
它提供类似
的输出{
Correct = 1;
EA = "50 Days ";
EB = "40 days";
EC = "90 days";
ED = "30 days";
}
我只需要使用密钥" EA"。
访问内容以前使用目标C,我曾经像
那样访问它[[json objectAtIndex:0] objectForKey:@"EA"]
现在当我试图像
那样访问它时json[0].objectForKey("EA") as? String
它说
类型的价值'任何'没有会员' objectForKey'
我该怎么办?
答案 0 :(得分:0)
Swift 2
(json[0] as! NSDictionary).objectForKey("EA") as? String
Swift 3& 4 强>
(json[0] as! NSDictionary).object(forKey: "EA") as? String