当密钥未知时获取对象?
我有一些如下所示的 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"];
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?
// 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"];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从
objectForKey:@"shops"
返回的对象实际上是一个NSDictionary
实例,而不是NSArray
,因为键实际上是字符串,而不是数字价值观。出于您的目的,您只需对生成的
NSDictionary
调用-allValues
即可。编辑:如果您需要对值进行排序,那么您可以执行以下操作:
首先,将传入的 JSON 更改为这种结构:
然后,您可以对数组中的对象进行排序。
The returned object from
objectForKey:@"shops"
is actually anNSDictionary
instance, not anNSArray
, since the keys are actually strings, not numeric values.For your purposes, you can simply call
-allValues
on the resultingNSDictionary
.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:
Then, you can have ordering of the objects in the array.