我正在尝试使用 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/