通过NSDictionary中迭代,并保存到对象类型的数组 [英] Iterate through NSDictionary and save it into an array of object type
问题描述
正如标题状态,我想通过一个NSDictionary的迭代和单个条目保存到对象类型的数组。
目前我正在努力读出的NSDictionary的一个条目,我不能简单地进入[指数]打电话给他们,向上计数。
我有一个名为客户端本地JSON文件,我进入迅速。该文件看起来是这样的:
{
顾客:
{
ID:3895,
手机:0787623,
时代:23,
customerSince:2008
},
{
ID:9843,
手机:7263549,
时代:39,
customerSince:2000
},
{
ID:0994,
手机:1093609,
时代:42,
customerSince:1997
}
]
}
我做了什么?
我创建了一个类ClientObjects,它看起来像这样:
进口基金会类ClientObjects { VAR ID:= 0;
VAR电话:INT = 0;
VAR年龄:= 0;
VAR customerSince:= 0;
}
接下来,我意识到JSON导入雨燕,它工作正常。
当我调试会议上, jsonResult
变量包含JSON数据。但不知何故,我无法管理的数据处理为对象类型的数组的 ClientObjects 的
//实例化ClientObjects为一个数组
变种clientsArray = [ClientObjects](); FUNC的getData(){ 如果让PATH = NSBundle.mainBundle()pathForResource(客户,ofType:JSON)。
{
如果让jsonData = NSData的(contentsOfFile:路径)
{
做{
如果让jsonResult =尝试NSJSONSerialization.JSONObjectWithData(jsonData,选择:NSJSONReadingOptions.MutableLeaves)作为?的NSDictionary
{
//打印(jsonResult [客户]);
//这个打印调用返回JSON数组的全部内容 如果让客户= jsonResult [客户]作为? [字符串:AnyObject]] {
在客户端{ clientsArray.append(客户端); }
捉让误差NSError {
打印(API错误:\\(error.debugDescription))
}
}
} }
}
我们的目标是,我可以打印出客户的单一属性,如:
clientsArray [0] .ID;
有人请给我一些建议对我的问题?
,首先让我们来看看ClientObject。
- 这应该是一个
结构
- 应该简单地命名为
客户端
- 的属性应该是没有默认值常量
- 它应该有一个failable初始化
- 的
电话
应该是字符串
(请相应更改JSON)
筛选
结构客户端{
让ID:诠释
让电话:字符串
让年龄:诠释
让customerSince:诠释 的init(JSON:[字符串:任何]){
让后卫
ID = json的[ID]作为?诠释,
手机= json的[电话]作为?串,
年龄= json的[时代]作为?诠释,
customerSince = json的[customerSince]作为?诠释其他{返回nil}
self.id = ID
self.phone =手机
self.age =年龄
self.customerSince = customerSince
}
}
现在让我们看JSON
FUNC的getData(){
做{
让后卫
PATH = NSBundle.mainBundle()pathForResource(客户,ofType:JSON),
jsonData = NSData的(contentsOfFile:路径),
jsonResult =尝试NSJSONSerialization.JSONObjectWithData(jsonData,选择:NSJSONReadingOptions.MutableLeaves)作为?的NSDictionary,
jsonClients = jsonResult [客户]作为? [字符串:任何]其他{}回报 让客户= jsonClients.flatMap(Client.init)//< - 现在你有你的客户端阵列 }赶上让误差NSError {
打印(API错误:\\(error.debugDescription))
}
}
As the title states, I would like to iterate through a NSDictionary and save the single entries into an array of object type. I am currently struggling to read out the single entries of the NSDictionary, as I cannot simply call them with entry[index] and count upwards.
I've got a local JSON file named "Clients", which I get into swift. The file looks like this:
{
"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
}
]
}
What did I do? I created a class ClientObjects, which looks like this:
import Foundation
class ClientObjects{
var id : Int = 0;
var phone : Int = 0;
var age : Int = 0;
var customerSince : Int = 0;
}
Next I realized the JSON import into Swift, which works properly.
When I debug the session, the jsonResult
variable contains the data of the JSON. But somehow I couldn't manage to process the data into the array of the object type 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)")
}
}
}
}
}
The goal is, that I can print out single attributes of clients, like:
clientsArray[0].id;
Can somebody please give me some advice on my issue?
First of all let's take a look at ClientObject.
- It should be a
struct
- It should be simply named
Client
- The properties should be constants without a default value
- It should have a failable initializer
- The
phone
should be aString
(please change your JSON accordingly)
Like this
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
}
}
Now let's read the JSON
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)")
}
}
这篇关于通过NSDictionary中迭代,并保存到对象类型的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!