AFN请求数据返回NSInlineData,json解析结果为nil

一般方式解析代码如下

 NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

解析结果dict为nil,后来打印了data的类型为NSInlineData

NSInlineData怎样处理,网上搜到的方式,很多都是按照下面方法改

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

manager.responseSerializer=[AFJSONResponseSerializer new];//AFHTTPResponseSerializer换成了AFJSONResponseSerializer

manager.responseSerializer.acceptableContentTypes=[NSSetsetWithObjects:@"application/json",@"text/html",@"text/javascript",@"text/json",@"text/plain",nil];

但是改后请求直接失败

失败的error信息如下

Error Domain=NSCocoaErrorDomain Code=3840 "Unable to convert data to string around character 76." UserInfo={NSDebugDescription=Unable to convert data to string around character 74.}

后来查到这个问题原因一般是response的编码问题

最终解决办法,请求依旧如下设置

AFHTTPSessionManager *manager = [AFHTTPResponseSerializer serializer];

manager.responseSerializer=[AFHTTPResponseSerializer   new];

manager.responseSerializer.acceptableContentTypes=[NSSetsetWithObjects:@"application/json",@"text/html",@"text/javascript",@"text/json",@"text/plain",nil];

解析结果用如下方法

NSStringEncoding enc = kCFStringEncodingUTF8;

NSString *strdata = [[NSString alloc]initWithData:responseData encoding:enc];

解析出了最终的结果,但是strdata中的汉字乱码,后来查看请求里header编码格式是Content-Type →application/json;charset=GBK

最终改为

    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);

NSString *strdata = [[NSString alloc]initWithData:responseData encoding:enc];

完美解决问题

你可能感兴趣的:(AFN请求数据返回NSInlineData,json解析结果为nil)