OGeek|极客世界-中国程序员成长平台

标题: iphone - key 未知时获取对象? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 09:20
标题: iphone - key 未知时获取对象?

我有一些如下所示的 json,我正试图将其转换为 nsdictionaries。我的问题是 1、5 和 4 是键,具有不可预测的值。我如何在不知道 key 的情况下获取每个对象 - {"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"];



Best Answer-推荐答案


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

关于iphone - key 未知时获取对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7648990/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4