Reputation: 5463
I'm pulling a JSON array of dictionaries trying to add them to a class I created and use them for a UITableView
. The JSON would look like this:
{
"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. Here's where I'm serializing my 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"]);
but that seems inefficient.
Do I need a for loop counting the number of dictionaries? Or a for (key, value)
loop? The fact that it's a bunch of dictionaries inside of an array named inventory
is really throwing me off. If it were JSON returning key:value pairs in a single dictionary I think I could figure it out on my own. I'm sort of stuck on what to do after putting my json["inventory"]
into a variable.
Upvotes: 0
Views: 936
Reputation: 285150
First of all cast the JSON serialization to something meaningful,
in this case 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.
let inventoryArray = dict["inventory"] as! [Dictionary<String, String>]
if inventory
is optional, use optional bindings
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"])
}
Upvotes: 1