基于JSON格式从NSArray解析值

时间:2014-08-06 09:07:28

标签: ios json parsing nsmutablearray

我有一个基于JSON格式的NSArray。我从网上请求它并将其保存在数组中。我正在尝试使用字典来获取" categoryname"的值。和" subscore"并将它们存储在新数组中,但它们仍然是空的。我是否必须使用JSON序列化将数组转换回NSData,还是有更直接的方法来实现这一目标?

NSArray详细分数:

    {
      "articles": [
        {
          "abstract": "text",  
          "title": "title"
        }
      ], 
      "subscore": 3, 
      "categoryname": "Reporting"
    }, 
    {
      "articles": [
        {
          "abstract": "text2",  
          "title": "title"
        }
      ], 
      "subscore": 1, 
      "categoryname": "Power"
    }]
}

代码:

for(int i = 0; i < [self.detailedscore count]; i++)
    {


        NSMutableDictionary * dc = [self.detailedscore objectAtIndex:i];

        NSString * score = [dc objectForKey:@"subscore"];
        NSString * categoryname = [dc objectForKey:@"categoryname"];

        [self.allscores addObject:subscore];
        [self.allcategories addObject:categoryname];

        for (NSString *yourVar in allcategories) {

            NSLog (@"Your Array elements are = %@", yourVar);


        }

4 个答案:

答案 0 :(得分:0)

如果你使用下面代码的数组 for(int i = 0; i&lt; [self.detailedscore count]; i ++)     {

    NSMutableDictionary * dc = [self.detailedscore objectAtIndex:i];

    NSString * score = [dc objectForKey:@"subscore"];
    NSString * categoryname = [dc objectForKey:@"categoryname"];

    [self.allscores score];
    [self.allcategories addObject:categoryname];

    for (NSString *yourVar in allcategories) {

        NSLog (@"Your Array elements are = %@", yourVar);


    }

答案 1 :(得分:0)

{} ----&gt;是指字典,[] ---&gt; array .....这是我遵循的规则,同时将来自webservices的返回值作为NSArray或NSDictionary .... 根据您当前的JSON格式,这可能会给您一个想法

NSMutableArray *categoryArray = [NSMutableArray new];
for (NSDictionary *childDict in self.detailedscore)
{
    [categoryArray addObject:[childDict objectForkey:@"categoryname"]];
}

答案 2 :(得分:0)

问题不在数组或字典或Web请求中。我没有分配NSMutableArrays所以它们一直都是空的。该代码适用于从数组中提取值,以防任何人想要使用它。

答案 3 :(得分:-1)

希望这会有所帮助。

[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * response,NSData * data,NSError * connectionError){         if(!connectionError){             NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:数据选项:NSJSONReadingAllowFragments错误:&amp; connectionError];             NSLog(@“Dict%@”,dict);             BOOL isValid = [NSJSONSerialization isValidJSONObject:dict];             if(isValid){                 [target getJSONFromresponseDictionary:dict forConnection:strTag error:connectionError];             }             其他{                 NSString * strResponse = [[NSString alloc] initWithData:数据编码:NSUTF8StringEncoding];                 [target getStringFromresponseDictionary:strResponse forConnection:strTag error:error];             }