【问题标题】:Accessing values of unknown Dictionary Keys访问未知字典键的值
【发布时间】:2012-01-27 09:17:16
【问题描述】:

我的 JSON 响应如下所示:

    {
    "themes": [
        [
            "Direction des Routes Secteur de Pithiviers ",
            "mairies",
            "Morailles 45300 PITHIVIERS LE VIEIL ",
            "0238345744",
            "48.823042",
            "2.365907"
        ],
        [
            "Crédit Mutuel Du Centre ",
            "banques",
            "agence de Pithiviers  33 r Am Gourdon 45300 PITHIVIERS",
            "0820834080",
            "48.703042",
            "2.145907"
        ]
    ]
}

如您所见,所有的键都是未知的,我没有Key:value,所以,我如何引用每个值。

NSDictionary *allThemesDict=[[request responseString]JSONValue];
 NSArray *allThemesValues=[allThemesDict objectForKey:@"themes"];
    for (int i=0; i<[allThemesValues count]; i++) {
        NSDictionary *currentTheme=[allThemesValues objectAtIndex:i];//here i get the first 6 values, how can i display it?
        }

【问题讨论】:

    标签: objective-c ios json nsarray nsdictionary


    【解决方案1】:

    它们是数组,而不是字典。所以你可以像这样抓取数组:

    NSDictionary *allThemesDict = [[request responseString] JSONValue];
    NSArray *allThemesValues = [allThemesDict objectForKey:@"themes"];
    for (int i=0; i<[allThemesValues count]; i++) {
        NSArray *currentTheme = [allThemesValues objectAtIndex:i];
        NSLog(@"currentTheme = %@", currentTheme);
    
        // Then access [currentTheme objectAtIndex:1] for example to get "mairies" in the first case.
    }
    

    【讨论】:

      【解决方案2】:

      您的示例中只有一个键:顶级字典有一个称为“主题”的键。其他一切都是数组或原语。

      假设您事先不知道“主题”键将被称为“主题”,您可以通过遍历字典来发现它。您可能会遇到一个问题,如果您不知道键是什么,您可能对数据了解不够,无法预测值的类型和内容。这里的解决方案是与服务器开发人员就数据格式的规范达成一致。作为参考,您可以像这样遍历字典(方法不止一种):

      for (id key in myDictionary) {
          //...
      }
      

      【讨论】:

        【解决方案3】:

        您只是想遍历数组吗?在这种情况下,这样的事情可能会起作用:

            NSDictionary *currentTheme=[allThemesValues objectAtIndex:i];
                for (id item in currentTheme) {
                    NSLog(@"item: %@", item);
                }
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-10-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多