Reputation: 2766
I am trying to parse a JSON
file with some tags and sub tags. I am doing this by creating a NSDictionary
. From this I create a NSDictionary
from a certain tag. This NSDictionary
contains the properties I want to parse. So I am trying to loop over the NSDictionary
, but it is not working. I tried many variants of this, but it keeps giving me compile time errors.
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(JSONData, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
var devices:NSDictionary = jsonResult.objectForKey("devices") as NSDictionary
for device:NSDictionary in devices{
device.objectForKey("id")
//etc
//etc
}
I get the following error:
'(key: AnyObject, value: AnyObject)' is not convertible to 'NSDictionary'
on the for each loop line. I've also tried casting it to NSDictionary after, but then I get the same error.
For clarification, this is an example of what my json file looks like:
{
"global":{
//etc
},
"user":{
//etc
},
"devices":[
{
"id":16108,
//etc
},
{
“id”:12310,
//etc
},
//etc
},
etc obviously means theres more data, this is just a basic outline. I am trying to read the properties of the devices
Upvotes: 4
Views: 6292
Reputation: 418
Works for me:
var error: NSError?
var jsonResult = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary
var devices = jsonResult.objectForKey("devices") as NSArray?
if devices != nil {
for device in devices! {
var deviceId = device.objectForKey("id") as NSNumber
println("deviceId: \(deviceId)")
}
}
Upvotes: -1
Reputation: 14169
The issue here is that objectForKey("devices")
returns an NSArray
and not a NSDictionary
Upvotes: 3