如何从 Objective C 中的 NSDictionary 获取键值?

Posted

技术标签:

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

我有一本字典:


  "FirstName" : "Katie",
  "SecondName" : "Brown"

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

【问题讨论】:

Get all keys of an NSDictionary 不显示为有效的 JSON if ([dict objectForKey:@"Firstname"] != nil) // key not null 可以使用 NSArray *arrKey = [dict allKeys]; NSArray *arrVal = [dict allValues]; @Shubhank 我没有从谷歌找到答案 【参考方案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。

【讨论】:

请在您的回答中添加解释

以上是关于如何从 Objective C 中的 NSDictionary 获取键值?的主要内容,如果未能解决你的问题,请参考以下文章