【问题标题】:how can i get out the values from json and show them in NSLog我如何从 json 中取出值并在 NSLog 中显示它们
【发布时间】:2012-06-05 08:50:58
【问题描述】:

你好,我为 web 服务创建了一个 json 字符串,我想输出名称和描述以在 NSLog 中显示它。我怎样才能做到这一点。到目前为止,这是我的代码:

    dic = [NSJSONSerialization JSONObjectWithData:result options:kNilOptions error:nil];


NSLog(@"Results %@",[NSString stringWithFormat:@"%@",[[dic objectForKey:@"d"]objectForKey:@"Name"]]);

我得到这个错误:

-[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x6b50f30

当我在我的字典中创建一个 NSLog 时,我得到了这个:

{
d = "{
\n  \"Name\": \"Apple\",
\n  \"Beschreibung\": \"Steve Jobs ist tot\"}";
}

我来自 werbservice 的 json 字符串如下所示:

string json = @"{
""Name"": ""Apple"",
""Beschreibung"": ""Steve Jobs ist tot""}";

【问题讨论】:

  • 您的网络服务返回一个 JSON 字符串。字符串的 contents 是字典的 JSON 表示。也就是说,字典已被序列化为字符串,然后该字符串已被序列化为其 JSON 表示形式。

标签: asp.net ios xcode json dictionary


【解决方案1】:

做这种嵌套的日志记录:

NSLog(@"Results %@",[NSString stringWithFormat:@"%@",[[dic objectForKey:@"d"]objectForKey:@"Name"]]);

真的很棘手。我猜想返回的任何对象“d”不一定是 NSDictionary 对象,也许是 NSArray ?

试试这样的:

NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:result options:kNilOptions error:nil];

// this gives the whole NSDictionary output:
NSLog( @"Results %@", [dic description] );

// get the dictionary that corresponds to the key "d"
NSDictionary * dDic = [dic objectForKey: @"d"];
if(dDic)
{
    NSString * nameObject = [dDic objectForKey: @"Name"];
    if(nameObject)
    {
        NSLog( @"object for key 'Name' is %@", nameObject );
    } else {
        NSLog( @"couldn't get object associated with key 'Name'" );
    }
} else {
    NSLog( @"couldn't get object associated with key 'd'") );
}

看看它是否能帮助你弄清楚你的假设在哪个级别和哪个对象上被打破了。

【讨论】:

  • +1,但在记录对象时几乎没有理由自己调用-description。这就是“%@”格式说明符已经做的事情。只需执行NSLog(@"Results %@", dic);。顺便说一句,dic 也可能不是字典,就像 [dic objectForKey:@"d"] 可能不是一样。
  • 是的。旧习惯对我来说很难改掉(即在 NSArray 和 NSDictionary 对象上调用“description”),但我知道将对象发送到“%@”NSLog 格式说明符会打印出事物的描述。这里的想法是让 Eray 找出他的 JSON 输出的哪一部分与他的假设(一切都是 NSDictionary)不匹配。
  • 当程序转到 NSString * nameObject = [dDic objectForKey: @"Name"];它得到错误
  • 你能说出你真正到达那里的是什么样的物体(以及它的内容是什么)?
  • 字典描述输出为:Results { d = "{ \n \"Name\": \"Apple\", \n \"Beschreibung\": \"Steve Jobs ist tot\" }"; }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多