iphone - 带有 bool 值的 AFNetworking JSON 请求

标签 iphone ios json afnetworking

我正在尝试使用 AFNetworking 发送 JSON 请求,但在将值转换为 {"value": true} 的 json 形式时遇到了问题。相反,我得到:{"value": 1}

这基本上是我创建请求的方式:

NSMutableURLRequest *request =
    [self.httpClient requestWithMethod:@"POST"
                                  path:url
                            parameters:@{@"value": @YES}];

AFJSONRequestOperation *operation =
    [AFJSONRequestOperation JSONRequestOperationWithRequest:request ...];
    [operation start];

我是不是漏掉了一些微不足道的东西? :)

最佳答案

简答: 确保您运行的是最新版本的 AFNetworking .根据您提供的代码,我认为这就是问题所在。

长答案: 我已尝试使用最新版本的 AFNetworking 重现您描述的问题我不能。我研究了 AFNetworking 以了解 JSON 的编码是如何完成的。 AFHTTPClient.m:442使用 NSJSONSerialization对 JSON 请求进行编码。我想出了以下代码来测试这个问题:

NSError* error = nil;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:@{@"value" : @YES} options:0 error:&error];
NSLog(@"Resulting JSON:\n\n%@\n", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);

输出:

{"value":true}

所以 @YES 应该这样做。请注意,请确保在您的代码中使用@(YES),因为它将输出为1 而不是true

NSError* error = nil;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:@{@"value" : @(YES)} options:0 error:&error];
NSLog(@"JSON:%@", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);

输出:

{"value":1}

有了这个,我经历了并试图弄清楚 AFHTTPClient 需要如何配置才能发送一个 bool 作为 1/0 而不是 true/false 并且找不到任何。这是我的网络代码。

AFHTTPClient* httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://<SERVER HERE>"]];
[httpClient setParameterEncoding:AFJSONParameterEncoding];
NSMutableURLRequest *jsonRequest = [httpClient requestWithMethod:@"POST" path:@"/" parameters:@{@"value": @YES}];

AFHTTPRequestOperation *jsonOperation = [AFJSONRequestOperation JSONRequestOperationWithRequest:jsonRequest success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
    NSLog(@"Success");
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
    NSLog(@"Failure");
}];
[jsonOperation start];

关于iphone - 带有 bool 值的 AFNetworking JSON 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14023565/

相关文章:

iphone - 在 iPhone 上接收图像(TCP 客户端)

c# - 多平台支持的 WCF Restful 服务文件上传

ios - 如何在界面生成器中使用框架中的 UIView 子类

ios - 在后台模式下在 iOS 模拟器中使用高速公路行驶/城市行驶

javascript - 使用 jQuery 在另一个 div 中克隆选定的选项

Android Kotlin + Klaxon - 解析 JSON 根数组

ios - iOS 中的相机和照片库

ios - 带有 2 个选项卡的选项卡栏 Controller 启动 View 同时加载

php - iOS Swift 5 - 通过调用 PHP 函数使用服务器上传文件

javascript - 从多个表加载后触发事件