AFNetworking将JSON作为POST请求的参数发送

AFNetworking将JSON作为POST请求的参数发送

我针对同一问题做了几个答案...但是无法弄清楚这个问题..我收到了这个错误


  *由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'* + [NSJSONSerialization
  dataWithJSONObject:options:error:]:JSON中的无效顶级类型
  写'


我的代码是:

NSDictionary *loginDict=[[NSDictionary alloc] initWithObjectsAndKeys:password.text,@"password",userName.text,@"userName",nil];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:loginDict                                                           options:NSJSONWritingPrettyPrinted                                                              error:&error];
if (jsonData) {
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
} else {
        NSLog(@"Got an error: %@", error);
}


 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
 manager.requestSerializer = [AFJSONRequestSerializer serializer];
 [manager.requestSerializer setTimeoutInterval:20];
 [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
 [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
 manager.responseSerializer = [AFJSONResponseSerializer serializer];
 manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];

[manager POST:baseUrlLogin parameters:jsonString
         success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
}];

最佳答案

尝试这个

直接在通话中通过loginDict并检查

manager.requestSerializer = [AFJSONRequestSerializer serializer];
/*
[manager.requestSerializer setTimeoutInterval:20];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
 manager.responseSerializer = [AFJSONResponseSerializer serializer];
 manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
 */
[manager POST:baseUrlLogin parameters: loginDict
     success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

关于ios - AFNetworking将JSON作为POST请求的参数发送,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37110433/

10-11 12:18