OGeek|极客世界-中国程序员成长平台

标题: ios - AFNetworking 中的 JSON 错误 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 08:24
标题: ios - AFNetworking 中的 JSON 错误

我正在尝试使用 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) requestNSString *)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。

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



Best Answer-推荐答案


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

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

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

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

关于ios - AFNetworking 中的 JSON 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24529755/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4