IOS中复杂JSON对象的解析

时间:2022-06-16 05:59:56

近期在工作中遇到的一个小问题。
向服务器发送请求数据的时候要使用到JSON,所以不能使用AFNetWorking了.因为默认的参数拼接方式不同

/** *  请求成功后的回调 * *  @param json 服务器返回的JSON数据 */typedefvoid (^A8HttpSuccess)(id jsondic); /** *  请求失败后的回调 * *  @param error 错误信息 */typedefvoid (^A8HttpFailure)(NSError *error);

/** *  同步与异步请求 * *  @param url     请求的URL *  @param isAsy   是否为异步 *  @param params  参数字典 *  @param success 成功的块代码回掉返回字典 *  @param failure 失败的块代码回掉返回error */ + (void)requestWithMethodPosturl:(NSString *)url isAsy:(Boolean)isAsy params:(NSDictionary *)params success:(A8HttpSuccess)success failure:(A8HttpFailure)failure{        //把字典转换成jsondata    NSError *error = nil;    NSData *jsonData = [NSJSONSerializationdataWithJSONObject:params                                                       options:NSJSONWritingPrettyPrinted                                                         error:&error];    //输出请求json    NSString* str = [[NSStringalloc] initWithData:jsonData encoding:NSUTF8StringEncoding];    NSLog(@"str=%@",str);        NSURL *baseURl = [NSURLURLWithString:url];    NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:baseURl];    [request setTimeoutInterval:2.0f];    [request setHTTPMethod:@"POST"];    [request setHTTPBody:jsonData];    if (isAsy) {        //是异步的请求        //异步        [NSURLConnectionsendAsynchronousRequest:request queue:[NSOperationQueuemainQueue] completionHandler:^(NSURLResponse *reponse, NSData *data, NSError *error) {            if (data != nil) {                         NSDictionary *dicJson = [selfdictionaryWithJsonData:data];                 if (success) {                    success(dicJson);                }                            } elseif (data == nil && error == nil) {                NSLog(@"接收到空数据");            } else {                                if (failure) {                    failure(error);                }                NSLog(@"%@", error.localizedDescription);            }        }];    }else{        //同步请求        NSError *synError;        NSData *data = [NSURLConnectionsendSynchronousRequest:request returningResponse:nilerror:&synError];        if (data !=nil) {                NSDictionary *dicJson = [selfdictionaryWithJsonData:data];            if (success) {                success(dicJson);            }                    }elseif(data == nil && error == nil){            NSLog(@"接收到空数据");        }else {            if (failure) {                failure(synError);            }            NSLog(@"%@", error.localizedDescription);        }    }    }//因为接收到的JSON不是合法JSON 带有反斜杠 和多余的引号 ,这里我采用了一个比较笨的办法进行处理
先把DATA转成字符串过滤掉反斜杠与多余的引号,然后再转为Data再用NSJSONSerialization解析成字典
2014-04-11 14:14:40.118 A8LOGIN[9378:a0b] 返回的数据{"desc":"注册成功","flag":0,"code":100,"msg":"{\"uid\":8053,\"uName\":\"fucklodalv20\",\"pwd\":\"\",\"token\":\"0822ka6h9485ituo7d64qx618\",\"question\":\"\"}"} 2014-04-11 14:14:40.119 A8LOGIN[9378:a0b] 过滤后的{"desc":"注册成功","flag":0,"code":100,"msg":"{"uid":8053,"uName":"fucklodalv20","pwd":"","token":"0822ka6h9485ituo7d64qx618","question":""}"} 2014-04-11 14:14:40.119 A8LOGIN[9378:a0b] 再次过滤后的{"desc":"注册成功","flag":0,"code":100,"msg":{"uid":8053,"uName":"fucklodalv20","pwd":"","token":"0822ka6h9485ituo7d64qx618","question":""}} 2014-04-11 14:14:40.119 A8LOGIN[9378:a0b] token======注册成功 2014-04-11 14:14:40.120 A8LOGIN[9378:a0b] token======0822ka6h9485ituo7d64qx618 +(NSDictionary *)dictionaryWithJsonData:(NSData *)data{    NSString *str = [[NSStringalloc]initWithData:data encoding:NSUTF8StringEncoding];        NSLog(@"返回的数据%@",str);    NSMutableString *strM = [NSMutableStringstringWithString:str];    [strM replaceOccurrencesOfString:@"\\"withString:@""options:0range:NSMakeRange(0, strM.length)];    NSLog(@"过滤后的%@\n",strM);        [strM replaceOccurrencesOfString:@"\"{"withString:@"{"options:0range:NSMakeRange(0, strM.length)];        [strM replaceOccurrencesOfString:@"}\"}"withString:@"}}"options:0range:NSMakeRange(0, strM.length)];        NSLog(@"再次过滤大括号引号后的%@\n",strM);            //再次把nsstring 转换成 data    NSData *jsonData = [strM dataUsingEncoding:NSUTF8StringEncoding];    //重新解析json 生成字典    NSDictionary *dic = [NSJSONSerializationJSONObjectWithData:jsonData options:NSJSONReadingMutableLeaveserror:nil];        return dic;    }