当密钥未知时获取对象?

发布于 2024-12-08 05:27:36 字数 374 浏览 1 评论 0原文

我有一些如下所示的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

雄赳赳气昂昂 2024-12-15 05:27:36

objectForKey:@"shops" 返回的对象实际上是一个 NSDictionary 实例,而不是 NSArray,因为键实际上是字符串,而不是数字价值观。

出于您的目的,您只需对生成的 NSDictionary 调用 -allValues 即可。

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"];
  //...
}

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"];
  //...
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文