正如标题所述,我想迭代一个NSDictionary并将单个条目保存到一个对象类型的数组中。 我目前正在努力读出NSDictionary的单个条目,因为我不能简单地用条目[index]调用它们并向上计数。
我有一个名为&#34的本地JSON文件;客户端",我快速进入。该文件如下所示:
{
"clients": [
{
"id": 3895,
"phone": 0787623,
"age" : 23,
"customerSince" : 2008
},
{
"id": 9843,
"phone": 7263549,
"age" : 39,
"customerSince" : 2000
},
{
"id": 0994,
"phone": 1093609,
"age" : 42,
"customerSince" : 1997
}
]
}
我做了什么? 我创建了一个ClientObjects类,如下所示:
import Foundation
class ClientObjects{
var id : Int = 0;
var phone : Int = 0;
var age : Int = 0;
var customerSince : Int = 0;
}
接下来我意识到JSON导入Swift,它可以正常工作。
当我调试会话时,jsonResult
变量包含JSON的数据。但不知怎的,我无法将数据处理到对象类型 ClientObjects 的数组中。
// instantiate the ClientObjects as an Array
var clientsArray = [ClientObjects]();
func getData() {
if let path = NSBundle.mainBundle().pathForResource("Clients", ofType: "json")
{
if let jsonData = NSData(contentsOfFile:path)
{
do {
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableLeaves) as? NSDictionary
{
//print(jsonResult["clients"]);
// this print call returns the whole content of the JSON array
if let clients = jsonResult["clients"] as? [[String: AnyObject]] {
for client in clients {
clientsArray.append(client);
}
catch let error as NSError {
print("API error: \(error.debugDescription)")
}
}
}
}
}
目标是,我可以打印出客户的单个属性,例如:
clientsArray[0].id;
有人可以就我的问题给我一些建议吗?
答案 0 :(得分:1)
struct
Client
phone
应为String
(请相应更改您的JSON)喜欢这个
struct Client {
let id: Int
let phone: String
let age: Int
let customerSince: Int
init?(json:[String:Any]) {
guard let
id = json["id"] as? Int,
phone = json["phone"] as? String,
age = json["age"] as? Int,
customerSince = json["customerSince"] as? Int else { return nil }
self.id = id
self.phone = phone
self.age = age
self.customerSince = customerSince
}
}
func getData() {
do {
guard let
path = NSBundle.mainBundle().pathForResource("Clients", ofType: "json"),
jsonData = NSData(contentsOfFile:path),
jsonResult = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableLeaves) as? NSDictionary,
jsonClients = jsonResult["clients"] as? [[String: Any]] else { return }
let clients = jsonClients.flatMap(Client.init) // <- now you have your array of Client
} catch let error as NSError {
print("API error: \(error.debugDescription)")
}
}
答案 1 :(得分:0)
您必须创建ClientObjects
个对象并将值分配给相应的属性。
...
let jsonResult = try NSJSONSerialization.JSONObjectWithData(jsonData, options: []) as! [String:AnyObject]
if let clients = jsonResult["clients"] as? [[String: Int]] {
for client in clients {
let newClient = ClientObjects()
newClient.id = client["id"]!
newClient.phone = client["phone"]!
newClient.age = client["age"]!
newClient.customerSince = client["customerSince"]!
clientsArray.append(newClient);
}
}
...
建议在这种情况下使用单数形式命名类ClientObject
if - let
行中没有NSDictionary
或基金会类型,例如MutableLeaves
或NSJSONSerialization
选项。