[英]Iterate through a JSON named array of dictionaries with swift 2.1
I'm pulling a JSON array of dictionaries trying to add them to a class I created and use them for a UITableView
. 我正在拉字典的JSON数组,试图将它们添加到我创建的类中,并将其用于UITableView
。 The JSON would look like this: JSON如下所示:
{
"inventory":[
{
"item":"item 1",
"description":"item 1 description",
"quantityOnHand":"42",
"supplier_id":"1",
"supplierName":"Supplier 1"
},
{
"item":"item 2",
"description":"item 2 description",
"quantityOnHand":"1001",
"supplier_id":"1",
"supplierName":"Supplier 1"
} ...
and so on... 等等...
I'm grabbing all this in my viewDidLoad()
and trying to add each dictionary to a class (called Inventory
) to work with later. 我要在viewDidLoad()
抓取所有这些内容,并尝试将每个字典添加到一个类(称为Inventory
)中,以便以后使用。 Here's where I'm serializing my JSON: 这是我要序列化JSON的位置:
override func viewDidLoad() {
super.viewDidLoad()
let urlString = "my url to json data";
let session = NSURLSession.sharedSession();
let url = NSURL(string: urlString)!;
session.dataTaskWithURL(url) { (data: NSData?, response:NSURLResponse?, error: NSError?) -> Void in
if let responseData = data {
do {
let json = try NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.AllowFragments)
print(json) //this prints out the above formatted json
if let dict = json as? Dictionary<String, AnyObject> {
print(dict["inventory"]![0]!["description"]);
print(dict["inventory"]![0]!["item"]);
print(dict["inventory"]![0]!["quantityOnHand"]);
}
} catch {
print("Could not serialize");
}
}
}.resume()
}
I'm able to print out each value using something like print(dict["inventory"]![0]!["description"]);
我可以使用诸如print(dict["inventory"]![0]!["description"]);
东西打印出每个值print(dict["inventory"]![0]!["description"]);
but that seems inefficient. 但这似乎效率很低。
Do I need a for loop counting the number of dictionaries? 我是否需要for循环来计算字典的数量? Or a for (key, value)
loop? 还是for (key, value)
循环? The fact that it's a bunch of dictionaries inside of an array named inventory
is really throwing me off. 它是一个名为inventory
的数组中的一堆字典,这一事实真的使我失望。 If it were JSON returning key:value pairs in a single dictionary I think I could figure it out on my own. 如果是JSON在单个字典中返回key:value对,我想我可以自己弄清楚。 I'm sort of stuck on what to do after putting my json["inventory"]
into a variable. 将json["inventory"]
放入变量后,我有点想做什么。
First of all cast the JSON serialization to something meaningful, 首先,将JSON序列化转换为有意义的内容,
in this case Dictionary<String, AnyObject>
在这种情况下Dictionary<String, AnyObject>
let json = try NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.AllowFragments) as! Dictionary<String, AnyObject>
Then retrieve the array of dictionaries, the JSON string reveals that it contains only String
types. 然后检索字典数组,JSON字符串显示它仅包含String
类型。
let inventoryArray = dict["inventory"] as! [Dictionary<String, String>]
if inventory
is optional, use optional bindings 如果inventory
是可选的,请使用可选的绑定
if let inventoryArray = dict["inventory"] as? [Dictionary<String, String>] { }
Now you can get the items in the array with a simple loop, any type casting is not needed. 现在,您可以通过简单的循环获取数组中的项目,不需要任何类型转换。
for anItem in inventoryArray {
print("description:", anItem["description"])
print("item: ", anItem["item"])
print("quantityOnHand: ", anItem["quantityOnHand"])
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.