我继承了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转换为可变对象。我发现AFJSONRequestOperation上有一个JSONReadingOptions属性,但我不知道如何设置它,因为我直接使用AFHTTPClient。
发布于 2013-10-25 16:56:44
这很简单。
[__instance registerHTTPOperationClass:[AFJSONRequestOperation class]];要这样做:
[__instance registerHTTPOperationClass:[CustomClassJSONRequestOperation class]];在CustomClassJSONRequestOperation.m中,只需这样写:
- (id)responseJSON {
[self setJSONReadingOptions: NSJSONReadingMutableContainers | NSJSONReadingAllowFragments];
return [super responseJSON];
}发布于 2013-03-17 00:17:12
我的一个请求失败并返回错误:
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错误页面……
长话短说,在你烦恼之前,请确保响应不只是格式不佳,而且它首先就存在。
https://stackoverflow.com/questions/14973288
复制相似问题