【问题标题】:Getting json data from NSDictionary从 NSDictionary 获取 json 数据
【发布时间】:2013-06-18 00:10:48
【问题描述】:

我正在尝试从简单的 json 响应中获取数据。

第一个日志显示我找到了一个名为 access_token 的项目,但是我不能从中使用 objectForKey,我得到[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x72de3b0

我做错了什么?

 for(NSDictionary *item in authResponse)
    {
        NSString *s1 = @"access_token";
        NSString *s2 = [item description];

        NSLog(@"access desc: %@", [item description]);
        if([s1 isEqualToString:s2]){
            NSLog(@"Item: %@", [item objectForKey:@"access_token"]);
        }
    }

【问题讨论】:

  • 您在 NSString 对象上调用 objectForKey,而不是 NSDictionary 对象。
  • 我的 json 对象是一个正确的 json 对象,那我该如何把我的 json 字符串变成字典呢?

标签: objective-c json nsdictionary


【解决方案1】:

authResponse 对象是一个NSDictionary 对象,但是它会在其中包含许多其他类型,包括其他NSDictionary 对象。您需要更加小心地解释每个成员:

for (NSObject *item in authResponse)
{
    if ([item isKindOfClass:[NSDictionary class]])
    {
        NSDictionary *dictItem = (NSDictionary *)item;
        //  do thing with sub-dictionary
    }
    else if ([item isKindOfClass:[NSString class]])
    {
        NSString *stringItem = (NSString *)item;
        //  do thing with string item
    }
    else if ([item isKindOfClass:[NSNumber class]])
    {
        NSNumber *numberItem = (NSNumber *)item;
        //  do thing with number item
    }
}

【讨论】:

    猜你喜欢
    • 2018-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-23
    • 1970-01-01
    • 2015-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多