在AFJSONRequestOperation中设置JSONReadingOptions

时间:2013-02-20 06:02:38

标签: ios objective-c afnetworking nsjsonserialization

我继承了AFHTTPClient&我将AFJSONRequestOperation类注册为请求处理程序,如下所示

- (id)initWithBaseURL:(NSURL *)url {
    self = [super initWithBaseURL:url];
    if (!self) {
        return nil;
    }

    [self registerHTTPOperationClass:[AFJSONRequestOperation class]];
    [self setDefaultHeader:@"Accept" value:@"application/json"];
    self.parameterEncoding = AFJSONParameterEncoding;

    return self;
}

但是,我需要将解析后的json转换为Mutable对象。我发现AFJSONRequestOperation上有一个JSONReadingOptions属性,但我无法弄清楚如何设置它,因为我直接使用AFHTTPClient

2 个答案:

答案 0 :(得分:2)

很简单。

  1. 创建AFJSONRequestOperation的子类。
  2. 在AFHTTPClient的子类中更改此内容:
  3.  [__instance registerHTTPOperationClass:[AFJSONRequestOperation class]];
    

    到此:

    [__instance registerHTTPOperationClass:[CustomClassJSONRequestOperation class]];
    
    CustomClassJSONRequestOperation.m中的

    只需写下:

    - (id)responseJSON {
        [self setJSONReadingOptions: NSJSONReadingMutableContainers | NSJSONReadingAllowFragments];    
        return [super responseJSON];
    }
    

答案 1 :(得分:1)

我的一个请求失败并返回错误:

  

JSON文本没有以数组或对象和允许的选项开头   碎片未设置。

要设置JSONReadingOptions,我必须继承AFJSONRequestOperation,然后在静态工厂方法返回的实例上设置属性。

+ (instancetype)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest
                                        success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success
                                        failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON))failure
{
    AFJSONRequestOperation *requestOperation = [super JSONRequestOperationWithRequest:urlRequest success:success failure:failure];
    requestOperation.JSONReadingOptions = NSJSONReadingAllowFragments;
    return (MyRequestSubclass *)requestOperation;
}

然后,在初始化sharedClient时,在客户端中将子类设置为HTTPOperationClass

[__instance registerHTTPOperationClass:[AFJSONRequestOperation class]];

......然后,事实证明,我正在击打的api碰巧发生故障,所以它返回了一个html错误页...

长话短说,在你打扰之前,确保反应不仅形成不良,而且它首先存在。