AFNetworking的使用&json转字典

一.AFNetworking的简单使用:

导入头文件
    #import <AFNetworking.h>

    //1.创建会话管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //2.封装参数
    NSDictionary *dict = @{
                           @"appid":@"201211268888",
                           @"type":@"ios"
                           };
    //3.发送GET请求

    /*
     第一个参数:请求路径(NSString)+ 不需要加参数
     第二个参数:发送给服务器的参数数据
     第三个参数:progress 进度回调
     第四个参数:success  成功之后的回调(此处的成功或者是失败指的是整个请求)
     task:请求任务
     responseObject:注意!!!响应体信息--->(json--->oc))
     task.response: 响应头信息
     第五个参数:failure 失败之后的回调
     */

    [manager GET:@"http://..." parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"success--%@--%@",[responseObject class],responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"failure--%@",error);
    }];

遇到type类型无法解析时:进入AFURLResponseSerialization.m文件227行左右添加上需要解析的类型:

-    self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil];
+    self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];

请求时可能遇到的错误及解决方案:

1. error : JSON text did not start with array or object and option to allow fragments not set.

这是因为 AFNetworking默认把响应结果当成json来处理,(默认manager.responseSerializer = [AFJSONResponseSerializer serializer]) ,很显然,我们请求的百度首页 返回的并不是一个json文本,而是一个html网页,但是AFNetworking并不知道,它坚信请求的结果就是一个json文本!然后固执地以json的形式去解析,显然没办法把一个网页解析成一个字典或者数组,所以产生了上述错误.解决这种问题只需要在发送请求前加上:

manager.responseSerializer = [AFHTTPResponseSerializer serializer];

但这样的话可能会导致responseObject的输出类型为_NSInlineData,输入结果为这样:

(lldb) po responseObject
<7b226365 6c6c7068 6f6e6522 3a6e756c 6c2c2275 73657270 7764223a 22222c22 61646472 65737322 3a6e756c 6c2c2269 64223a30 2c227573 65726e61 6d65223a 22777037 227d>

因此在请求成功后要对respon进行一个data->json的转换:

NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"ResDic = %@",dic);

二.json转字典

- (NSDictionary *)parseJSONStringToNSDictionary:(NSString *)JSONString {
    NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
    return responseJSON;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容