【问题标题】:how to check condition for parsed elements in iphone如何检查iphone中已解析元素的条件
【发布时间】:2011-04-19 08:50:54
【问题描述】:

从我项目中的 Json 解析中,我得到了这些元素...

执行指令:-

NSArray *feed3 = (NSArray *)[feed valueForKey:@"type"];  
NSLog(@" %@",feed3);

在控制台中我得到了这个

( 状态,
照片,
链接,
视频)

现在我想检查这些元素的条件..

喜欢

if(type==staus){  
//do some thing  
} 

如何在 xcode 中做到这一点?

【问题讨论】:

标签: iphone json parsing


【解决方案1】:

我假设 feed3 是 JSON 解析器在解析了您在另一个问题中列出的 JSON 数据后返回的对象。在这种情况下:

* the top level object is an array
* every element in the array is an object/dictionary representing news
* this object/dictionary contains the following keys:
  * application (object/dictionary with two keys: id, name)
    * id (number)
    * name (string)
  * created_time (string)
  * from (object/dictionary with two keys: id, name)
    * id (number)
    * name (string)
  * icon (string)
  * id (string)
  * likes (object/dictionary with two keys: count, data)
    * count (number)
    * data (array)
      * every element in the array is an object/dictionary
      * this object/dictionary has two keys (id, name)
        * id (number)
        * name (string)
  * link (string)
  * name (string)
  * picture (string)
  * properties (array of objects/dictionaries)
  * type (string)
  * updated_time (string)

解析 JSON 数据时,了解数据的组织方式至关重要。我建议您在必须解析 JSON 时始终执行上述操作。

由于您对“类型”感兴趣,因此您需要遵循以下路径:

  • 遍历消息的顶层数组
    • 数组中的每个元素都是一个对象/字典
      • 此对象/字典有一个名为“type”的键

下面的代码应该可以解决问题:

for (NSDictionary *news in feed3) {
    NSString *type = [news objectForKey:@"type"];

    if ([type isEqualToString:@"status"]) {
       …
    }
    else if ([type isEqualToString:@"photo"]) { 
       …
    }
    else if ([type isEqualToString:@"link"]) { 
       …
    }
    else if ([type isEqualToString:@"video"]) { 
       …
    }
}

请注意,一般情况下,您应该使用-objectForKey: 而不是-valueForKey:

  • -objectForKey: 是在NSDictionary 中声明的方法,它用于获取存储在给定相应键的字典中的对象。
  • -valueForKey: 是一种 KVC 方法,用于另一个目的。特别是,它可以在您不期望时返回一个数组!

【讨论】:

  • 嘿..Bavarious...这是我得到的很好的解释..因为我是一个新人..请建议我在哪里可以学习这样的解析东西..任何好的网站或任何书,如果你能建议..非常感谢...接受和向上:)
  • @rathodrc 本质上是在密切关注数据。当您有行 JSON 数据时,将其粘贴到 jsonlint.com 上会很有用——它会告诉您数据是否有效,并以易于理解的方式格式化它们。
  • @rathodrc 但请注意,您已在另一个问题中发布不是原始 JSON 数据 - 这只是 NSLog() 打印数组和字典的方式。
【解决方案2】:

查看下方

for(int index = 0 ; index < [feed3 count] ; index++)
{
    NSString* tempString = [feed3 objectAtIndex:index];

    if([tempString isEqualToString:@"status"]) 
    {
      //Get value for status from value array
    }
    else if([tempString isEqualToString:@"photo"]) 
    {
      //Get value for photo from value array
    }
    else if([tempString isEqualToString:@"link"]) 
    {
      //Get value for link from value array
    }
    else if([tempString isEqualToString:@"video"]) 
    {
      //Get value for video from value array
    }
}

【讨论】:

  • 还是不行。 :-P JSON解析器返回的对象是一个由字典对象组成的数组。
猜你喜欢
  • 2014-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多