JSON 递归遍历算法(IOS)

调用时深度的default值为0

-(void)testPetch:(NSString*) json forDeep:(int) level

{
    NSString* result = @"";
    NSString* prevChar = @"";
    NSUInteger slen = [json length];
    BOOL needrec = NO;


    NSString* lStr = @"";
    
    for ( int i=0; i < slen; i++) {
        NSString* sc = [json substringWithRange: NSMakeRange(i,1)];
        
        if ([sc isEqualToString: @"{"] && (!needrec))
        {
            if ([result length]>0) {
                // delete left and right space
                [result stringByTrimmingCharactersInSet:[ NSCharacterSet whitespaceCharacterSet]];
                if ([[result substringWithRange: NSMakeRange(0,1)] isEqualToString: @","])
                {
                    result = [result substringWithRange: NSMakeRange(1,[result length]-1)];
                }
                NSLog( @"add (%d)deep json object :%@ ",level,result);
                result = @"";
            }
            else
            {
                NSLog( @"add (%d)deep json object : object name is null",level);
            }
            
            lStr = [json substringWithRange: NSMakeRange(i+1,slen-i-1)];
            break;
        }
        
        if ([sc isEqualToString: @"["] && (!needrec))
        {
            if ([result length]>0) {
                // delete left and right space
                [result stringByTrimmingCharactersInSet:[ NSCharacterSet whitespaceCharacterSet]];
                if ([[result substringWithRange: NSMakeRange(0,1)] isEqualToString: @","])
                {
                    result = [result substringWithRange: NSMakeRange(1,[result length]-1)];
                }
                NSLog( @"add (%d)deep json array : %@",level,result);
                result = @"";
            }
            else
            {
                NSLog( @"add (%d)deep json array : array name is null",level);
            }
            
            lStr = [json substringWithRange: NSMakeRange(i+1,slen-i-1)];
            break;
        }
        
        if ([sc isEqualToString: @"}"] && (!needrec))
        {
            NSLog( @"Add (%d) a member%@",level,result);
            level = level -1;
            result = @"";
            continue;
        }
        
        if ([sc isEqualToString: @"]"] && (!needrec))
        {
            NSLog( @"Add (%d) a array member%@",level,result);
            level = level -1;
            result = @"";
            continue ;
        }
        
        if ([sc isEqualToString: @"\""] && (![prevChar isEqualToString: @"\\"]))
        {
            needrec = !needrec;
        }
            
        result = [result stringByAppendingFormat: @"%@",sc];
            
        prevChar = sc;
        
    }

   

   // Loop

    if (0 < [lStr length])
    {
        [self testPetch:lStr forDeep:level+1];
    }
    
    return ;
}

你可能感兴趣的:(ios,json,算法,object,null,delete)