【问题标题】:How to get the key values from NSDictionary in Objective C?如何从 Objective C 中的 NSDictionary 获取键值?
【发布时间】:2016-08-31 06:49:16
【问题描述】:

我有一本字典:

{
  "FirstName" : "Katie",
  "SecondName" : "Brown"
}

如何从上述字典中获取键值“FirstName”和“SecondName”

【问题讨论】:

  • 不显示为有效的 JSON
  • if ([dict objectForKey:@"Firstname"] != nil) { // key not null }
  • 可以使用 NSArray *arrKey = [dict allKeys]; NSArray *arrVal = [dict allValues];
  • @Shubhank 我没有从谷歌找到答案

标签: ios objective-c


【解决方案1】:

试试这个代码:

NSData* yourJSONData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:yourJSONData options:0 error:nil];
NSArray *allTheKeys = [jsonObject allKeys];

【讨论】:

    【解决方案2】:

    你可以得到

    if ([yourDictname objectForKey:@"FirstName"] && [yourDictname objectForKey:@"SecondName"]) {
        // key exists.
    }
    else
    {
        // ...
    }
    

    或者你可以得到

    if ([[yourDictname allKeys] containsObject:@"FirstName"] && [[yourDictname allKeys] containsObject:@"SecondName"]) {
        // key exists.
    }
    

    【讨论】:

      【解决方案3】:

      您可以从字典中获取键数组,例如,

         NSDictionary *dic; // your dictionary here
      
      NSArray *allKeys = [dic allKeys];
      NSLog(@"all keys : %@",allKeys);
      

      您也可以获得相同的价值,例如[dic allValues]

      【讨论】:

        【解决方案4】:
        NSString *jsonString = @" {\"FirstName\" : \"Katie\",\"SecondName\" : \"Brown\"}";
        NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        for (NSString *key in dic.allKeys) {
            NSLog(@"key: %@ value: %@", key, dic[key]);
        }
        

        或试试JSONModel

        【讨论】:

        • 请在您的回答中添加解释
        猜你喜欢
        • 1970-01-01
        • 2021-07-09
        • 1970-01-01
        • 2014-03-16
        • 1970-01-01
        • 1970-01-01
        • 2017-03-27
        • 2015-11-24
        • 1970-01-01
        相关资源
        最近更新 更多