I have some json coming like the below, which i'm trying to turn into nsdictionaries. My problem is that the 1, 5 and 4 are keys, with unpredictable values. How would I get each object - {"id":"A","name":"Nike"} - without knowing the key?
开发者_StackOverflow中文版// JSON looks like:
{
"shops":
{
"1":{"id":"A","name":"Nike"},
"5":{"id":"G","name":"Apple"}
"4":{"id":"I","name":"Target"}
}
}
// how to step thru this?
NSArray *shopsArray = [[shopsString JSONValue] objectForKey:@"shops"];
The returned object from objectForKey:@"shops"
is actually an NSDictionary
instance, not an NSArray
, since the keys are actually strings, not numeric values.
For your purposes, you can simply call -allValues
on the resulting NSDictionary
.
NSDictionary *shops = [[shopsString JSONValue] objectForKey:@"shops"];
for(id obj in [shops allValues]) {
//do stuff with obj...
}
EDIT: If you need ordering of the values, then you can do something like the following:
First, change the incoming JSON to this kind of structure:
{
"shops":[
{"key":"1", "id":"A","name":"Nike"},
{"key":"5","id":"G","name":"Apple"},
{"key":"4", "id":"I","name":"Target"}
]
}
Then, you can have ordering of the objects in the array.
NSArray *shops = [[shopsString JSONValue] objectForKey:@"shops"];
for(NSDictionary *shop in shops) {
NSString *key = [shop objectForKey:@"key"];
//...
}
精彩评论