使用布尔值AFNetworking JSON请求

aby*_*byx 13 iphone json ios afnetworking

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

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

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

AFJSONRequestOperation *operation =
    [AFJSONRequestOperation JSONRequestOperationWithRequest:request ...];
    [operation start];
Run Code Online (Sandbox Code Playgroud)

我在这里错过了一些小事吗?:)

Pie*_*ard 14

简短回答: 确保您运行的是最新版本的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]);
Run Code Online (Sandbox Code Playgroud)

输出:

{"value":true}
Run Code Online (Sandbox Code Playgroud)

所以@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]);
Run Code Online (Sandbox Code Playgroud)

输出:

{"value":1}
Run Code Online (Sandbox Code Playgroud)

有了这个,我经历了并试图找出如何配置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];
Run Code Online (Sandbox Code Playgroud)