简体   繁体   English

使用布尔值AFNetworking JSON请求

[英]AFNetworking JSON request with a boolean

I'm trying to send a JSON request using AFNetworking and have a problem with making values be translated to the json form of {"value": true} . 我正在尝试使用AFNetworking发送JSON请求,并且在将值转换为{"value": true}的json形式时遇到问题。 Instead, I'm getting: {"value": 1} 相反,我得到: {"value": 1}

Here's basically how I'm creating the request: 这基本上就是我创建请求的方式:

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

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

Am I missing something trivial here? 我在这里错过了一些小事吗? :) :)

Short answer: Make sure you are running a recent version of AFNetworking . 简短回答:确保您运行的是最新版本的AFNetworking That's all I can see as the problem based on the code you've provided. 根据您提供的代码,这就是我所能看到的问题。

Long answer: I've tried reproducing the issue you're describing with the most recent versions of AFNetworking and I could not. 答案长:我已尝试使用最新版本的AFNetworking再现您所描述的问题, 我无法做到。 I dug into AFNetworking to see how the encoding of JSON is done. 我挖掘AFNetworking以了解JSON的编码是如何完成的。 AFHTTPClient.m:442 uses NSJSONSerialization to encode JSON requests. AFHTTPClient.m:442使用NSJSONSerialization来编码JSON请求。 I came up with the following code to test the issue: 我想出了以下代码来测试问题:

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]);

outputs: 输出:

{"value":true}

So @YES should do it. 所以@YES应该这样做。 As a note, be sure not to use @(YES) in your code as it will output as a 1 instead of true . 请注意,请确保不要在代码中使用@(YES) ,因为它将输出为1而不是true

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

outputs: 输出:

{"value":1}

With that I went through and tried to figure out how AFHTTPClient need to be configured to send out a bool as 1 / 0 instead of true / false and could not find any. 与我的经历,并试图找出需要多AFHTTPClient进行配置,以发送一个bool为1 / 0 ,而不是true / false ,但没有找到任何。 Here's my networking code. 这是我的网络代码。

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];

Since @YES is an NSNumber, NSJSONSerialization turns this to 0/1. 由于@YES是NSNumber,因此NSJSONSerialization将其转换为0/1。

I don't think there's a way other than @{@"value": (yesOrNo ? @"true" : @"false")} or using a different serialization class. 我认为除了@{@"value": (yesOrNo ? @"true" : @"false")}之外还有其他方式@{@"value": (yesOrNo ? @"true" : @"false")}或使用不同的序列化类。

For people who might be running into this issue, there's another reason why it might be happening. 对于可能遇到此问题的人来说,还有另一个可能发生这种情况的原因。

Make sure you set the parameterEncoding property of your AFHTTPClient subclass to AFJSONParameterEncoding , otherwise you'll run into the issue of NSNumber's initialization value not being correctly detected, and will see 0s and 1s being output instead by the encoder. 确保将AFHTTPClient子类的parameterEncoding属性设置为AFJSONParameterEncoding ,否则您将遇到NSNumber的初始化值未被正确检测的问题,并且将看到编码器输出0和1。

See this for reference as well. 请参阅此内容以供参考。

Hope this helps. 希望这可以帮助。

In the subclass of HTTPClient. 在HTTPClient的子类中。 Instead of: 代替:

self.responseSerializer = [AFJSONResponseSerializer serializer];

try with: 尝试:

$self.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];

I have the same error, I am sending the @YES but the services give me fail, so I create and string of a json and create an jsonObject like this: 我有同样的错误,我发送@YES,但服务给我失败,所以我创建和json的字符串,并创建一个像这样的jsonObject:

NSString* paramsString = @"{";
NSString* appending = [NSString stringWithFormat:@"\"%@\":%@,", KEY_CHECKED, (checked ? @"true" : @"false")];
paramsString = [paramsString stringByAppendingString: appending];
paramsString = [paramsString stringByAppendingString:@"}"];
id object = [NSJSONSerialization JSONObjectWithData:[paramsString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];

Use this object for send the post with AFNetworking 使用此对象通过AFNetworking发送帖子

[self postParameters:object];

for me works! 对我来说工作!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM