【发布时间】:2014-06-22 18:05:33
【问题描述】:
我正在尝试使用 AFNetworking 执行从 Web 服务返回 JSON 字符串的 GET 请求,但我从 AFNetworking 1.3.3 收到以下错误
@"JSON 文本没有以数组或对象开头,并且允许未设置片段的选项。"
这是我的 JSON,它是一个有效的 JSON 字符串,我使用了许多在线验证器来确保
"{\"ErrorCode\":0,\"VerCode\":\"8595\"}"
AFNetworking 代码不起作用
NSString *urlString = [BASE_URL stringByAppendingString:paramseters];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:BASE_URL]];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"GET"
path:urlString
parameters:nil];
AFJSONRequestOperation *operation =
[AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSDictionary *jsonDic = (NSDictionary *)JSON;
success(jsonDic);
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
CPError *cpError = [CPError CPErrorWithErrorCode:error.code errorDesc:error.localizedDescription];
failure(cpError);
}];
[operation start];
我能够使用以下代码将 JSON 解析为 NSDictionary,但我希望能够使用 AFNetworking 以利用它的内置功能,有没有办法让 AFNetworking 理解我的 JSON 字符串?
NSURL *url = [NSURL URLWithString:@"http://103.1.173.60/ims-mobile-wcf/MobileWCF.svc/AddUpdateMobileClient/123123/443da4444/1/1"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:120];
[request setHTTPMethod:@"GET"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSLog(@"%@",connectionError);
NSError *error = nil;
NSString *JSONString = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSDictionary *JSONDictionary =
[NSJSONSerialization JSONObjectWithData: [JSONString dataUsingEncoding:NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error: &error];
}];
【问题讨论】:
-
发布失败的代码,而不是其他有效的代码。使用 AFNetworking 检查 JSON 的要求。
-
就我个人而言,我会打破Charles Proxy 并确保发送什么以及返回什么。 (免费试用)。
-
@Zaph 我发布的代码指出问题不在于服务器响应,实际上是 AFNetworking
标签: iphone objective-c json ios7 afnetworking