我有一些json像下面这样,我正试图变成nsdictionaries。我的问题是1,5和4是键,具有不可预测的值。如何获得每个对象 - {“id”:“A”,“name”:“Nike”} - 不知道密钥?
// 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"];
答案 0 :(得分:3)
objectForKey:@"shops"
返回的对象实际上是NSDictionary
个实例,而不是NSArray
,因为这些键实际上是字符串,而不是数值。
出于您的目的,您只需在生成的-allValues
上致电NSDictionary
。
NSDictionary *shops = [[shopsString JSONValue] objectForKey:@"shops"];
for(id obj in [shops allValues]) {
//do stuff with obj...
}
编辑:如果您需要订购价值,那么您可以执行以下操作:
首先,将传入的JSON更改为这种结构:
{
"shops":[
{"key":"1", "id":"A","name":"Nike"},
{"key":"5","id":"G","name":"Apple"},
{"key":"4", "id":"I","name":"Target"}
]
}
然后,您可以对数组中的对象进行排序。
NSArray *shops = [[shopsString JSONValue] objectForKey:@"shops"];
for(NSDictionary *shop in shops) {
NSString *key = [shop objectForKey:@"key"];
//...
}