博客> iOS scoket接受数据以\r\n结束 怎么解析(这样子就能解析成一个个字典了,纯属做笔记而已)
iOS scoket接受数据以\r\n结束 怎么解析(这样子就能解析成一个个字典了,纯属做笔记而已)
1小时前 评论:0 阅读:114 eranthe

-(void)socket:(GCDAsyncSocket )sock didReadData:(NSData )data withTag:(long)tag { [_socket readDataWithTimeout:-1 tag:0]; NSString receiverStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSArray array= [receiverStr getJsonArray];

} -(NSArray*)getJsonArray{ if(self.length>0){

}else{
    return [NSArray array];
}
NSMutableArray *array=[NSMutableArray array];

NSInteger Num=0;
NSInteger Num1=0;
BOOL cor=YES;
BOOL can=NO;

NSInteger beg=0;

for (int i=0; i<self.length; i++) {
    char c=[self characterAtIndex:i];
    if(c=='{'&&cor){
        can=YES;
        Num++;
    }
    if(c=='['&&cor){
        can=YES;
        Num1++;
    }
    if(c==']'&&cor){
        Num1--;
    }
    if(c=='"'){
        cor=!cor;
    }
    if(c=='}'&&cor){
        Num--;
    }
    if(Num==0&#1==0&&can){
        [array addObject:[self substringWithRange:NSMakeRange(beg, i-beg+1)]];
        beg=i+1;
        can=NO;

    }
}
if(Num==0&#1==0){
    NSMutableArray *temp=[NSMutableArray array];
    for (NSString *mess in array) {
        NSLog(@"%@",mess);
        id json=[NSJSONSerialization JSONObjectWithData:[mess dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves|NSJSONReadingAllowFragments error:nil];
        if(json){
            [temp addObject:json];
        }
    }
    return temp;
}else{
    return [NSArray array];
}

}

收藏
0
sina weixin mail 回到顶部