【问题标题】:JSON error in AFNetworkingAFNetworking 中的 JSON 错误
【发布时间】:2014-07-02 11:17:46
【问题描述】:

我正在尝试使用 AFNetworking 库向这样的 URL 发送发布请求:

https://m.com/api/2.0/basic/sim_balance.json

这需要 URL 中的用户名和密码作为我的参数(作为 NSDictionary)。

URL 像这样返回 JSON:

{
    "valid_until": "2011-05-05 22:13:28",
    "sms": 0,
    "sms_super_on_net_max": 300,
    "voice_super_on_net": 0,
    "credits": "0.00",
    "bundles": [],
    "is_expired": true,
    "sms_super_on_net": 0,
    "voice_super_on_net_max": 3600,
    "data": 0
}

这是我的请求函数:

 +(void) request:(NSString *)endpoint : (NSDictionary *) parameters
    {
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        [manager POST:endpoint parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"JSON: %@", responseObject);
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Error: %@", error);
        }];
    }

我总是将此视为错误:

Error: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x904b7e0 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

我验证了 JSON 并且服务器正在发送有效的 JSON。

有人可以帮我解决这个问题吗?

【问题讨论】:

  • 您是否设置过AFHTTPRequestOperationManager 实例的requestSerializer 属性?
  • 不,我需要这样做吗?
  • 在您的失败块中,尝试使用operation.responseStringoperation.responseData 检查响应的原始内容。

标签: ios objective-c json ios7 afnetworking-2


【解决方案1】:

要让AFHTTPRequestOperationManager将请求体序列化为JSON,需要设置其requestSerializer的值:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager POST:....];

如果不设置 requestSerializer 属性,则 manager 对象默认使用x-www-form-urlencoded 序列化。

但请注意,AFHTTPRequestOperationManager 默认会处理 response 正文中的 JSON。

【讨论】:

  • 我已经添加了这个。但如果它默认发生,我为什么需要设置这个?
  • 哦,您是说用户名/密码可以在请求的 URL 中发送,所以服务器不希望请求正文中包含 JSON。我误读了你的问题。我想你可以无视这个答案。
  • 服务器在帖子正文中需要用户名和密码。
  • 好的。那么将 requestSerializer 设置为 AFJSONRequestSerializer 是否修复了错误?
  • 我现在无法测试该网站正在维护中。当他回来时,我会通知你的。我希望这能解决问题。
【解决方案2】:

感谢酯,我找到了解决方案。您还需要正确设置基本的身份验证标头。

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"Tom" password:@"test"];
[manager GET:endpoint parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {       
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Response data: %@",operation.responseData);      
    NSLog(@"Response String: %@",operation.responseString);     
    NSLog(@"Error: %@", error);
}];
}

【讨论】:

    猜你喜欢
    • 2012-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多