search

Home  >  Q&A  >  body text

objective-c - What is the reason why there are null and duplicates when traversing NSDictionary in iOS?

When I parse JSON, null and duplicate data will appear when traversing the dictionary content to the model in the last step. Every previous step is correct. I have this problem when I test the api of a friend's own server. I also used the news API in Baidu APIStore and had the same problem. Please tell me what I did wrong. Please enlighten me. Thank you!

The following is the code, using AFNetworking, there are 5 arrays in JSON, and the bottom is a screenshot of the console, using a for loop and a commented out for in, both have the same problem

    [manager POST:@"地址不便透露,抱歉" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"成功");
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSArray *jData = [responseObject objectForKey:@"array"];
            //NSLog(@"%@",jData);
            
            for (NSDictionary * dict in jData)
            {
                NSArray * keys=[dict allKeys];
                JKey * jKey=[[JKey alloc]init];
                /*
                for (NSString * str in keys) {
                    //对对象的属性一一赋值 KVC
                    [jKey setValue:[dict objectForKey:str] forKey:str];
                    if ([dict objectForKey:str] > 0) {
                        [self.testArray addObject:jKey];
                    }
                }
                 */
                for (NSInteger i=0; i<keys.count; i++) {
                    [jKey setValue:[dict objectForKey:keys[i]] forKey:keys[i]];
                    NSLog(@"jKey=%@",jKey.coverpath);
                }
            }
        }

phpcn_u1582phpcn_u15822840 days ago762

reply all(2)I'll reply

  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-02 09:36:28

    I tried it myself and it was no problem to assign values ​​one by one

    for (NSDictionary * dict in jData)
    {
        JKey * jKey=[[JKey alloc]init];
        jKey.title = [dict valueForKey:@"title"];
        jKey.link = [dict valueForKey:@"link"];
        jKey.Id = [dict valueForKey:@"id"];
        jKey.coverpath = [dict valueForKey:@"coverpath"];
        [self.testArray addObject:jKey];
    }

    reply
    0
  • 黄舟

    黄舟2017-05-02 09:36:28

    Try it with MJExtension
    for (NSInteger i = 0; i<array1.count; i++) {

    
         NormalModel * model = [NormalModel  objectWithKeyValues:array1[i]];
        
        [self.dataArray addObject:model];
    }

    reply
    0
  • Cancelreply