【问题标题】:Loop through JSON NSDictionary循环遍历 JSON NSDictionary
【发布时间】:2012-12-20 18:14:04
【问题描述】:

我正在尝试使用 PHP 以 JSON 格式打印 MySQL 结果集,并使用 iOS 读取它。

这是我的 JSON 字符串

[{"partnerid":"1","code":"SUMU6003","partnerName":"Company name","street":"Some Street 5323","zipCode":"8732","city":"Berlin","languages":"English","workers":"Name 1, Name 2","lineup":"Kids"},{"partnerid":"2","code":"DEMO8884","partnerName":"Partner 2","street":"Third street 2","zipCode":"383838","city":"Berlin","languages":"Greek","workers":"Petra","lineup":"Kids"}]

在这个方法中,我得到了NSDictionary

#pragma mark - ServiceConnectorDelegate -

-(void)requestReturnedData:(NSData *)data { 
    NSDictionary *dictionary = [NSDictionary dictionaryWithJSONData:data];
    # process dictionary and grep strings from json-string
    # ...
}

您能告诉我如何在循环中访问不同的结果集吗?我想分别访问每个键。

我知道NSDictionary 包含数据,因为NSLog(@"%@",dictionary); 打印:

2012-12-20 19:13:20.661 myapp[576:907] (
        {
        city = Berlin;
        code = SUMU6003;
        languages = English;
        lineup = Kids;
        partnerName = "Company name";
        partnerid = 1;
        street = "Some Street 5323";
        workers = "Name 1, Name 2";
        zipCode = 8732;
    },
        {
        city = Berlin;
        code = DEMO8884;
        languages = Greek;
        lineup = Kids;
        partnerName = "Partner 2";
        partnerid = 2;
        street = "Third street 2";
        workers = Petra;
        zipCode = 383838;
    }
)

非常感谢您的帮助。

【问题讨论】:

  • 那不是“JSON 字典”。它是一个包含多个 JSON 对象的 JSON 数组。 JSON 数组 == NSArray。 JSON 对象 == NSDictionary。当您对“字典”进行 NSLog 记录时,它会打印出 NSDictionaries 的 NSArray。

标签: php ios json nsarray nsdictionary


【解决方案1】:

有时内省在这里很有用。例如 NSLog(@"dictionary is of type: %@", [dictionary class]);

我之所以这么说是基于您的输出,看来字典实​​际上是一个包含两个 NSDictionaries 的数组。如果是这种情况,你会想做这样的事情:

for (NSDictionary *actualDictionary in dictionary<this is really an array>)
{
  NSString *myStringValue = [actualDictionary objectForKey:@"city"];
  // etc...
}

您必须首先找出您实际处理的数据类型。

【讨论】:

  • 返回:字典类型:__NSCFArray
  • 这正是人们所期望的。
  • 是的,这意味着我在上面为您布置的循环应该可以解决问题。
  • 嗨,HackyStack,正是我一直在寻找的,非常感谢,圣诞快乐!
【解决方案2】:

这样做:

#import &lt;objc/runtime.h&gt;

NSLog(@"The class name is %s", object_getClassName(dictionary);

【讨论】:

    【解决方案3】:

    您拥有的响应字典包含 字典数组,因此您可以通过快速枚举字典来运行字典值并将每个字典转换为字典并获取其值,如下所示:

    -(void)requestReturnedData:(NSData *)data { 
        NSDictionary *dictionary = [NSDictionary dictionaryWithJSONData:data];
        # process dictionary and grep strings from json-string
        for(id item in dictionary ) 
        {
            NSDictionary *dic = (NSDictionary *)item;
            NSLog(@"%@",[dic objectForKey:@"city"]);
            NSLog(@"%@",[dic objectForKey:@"code"]);
            ......
        }
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多