无法在ios中使用afnetworking发布JSON

时间:2015-09-08 07:26:21

标签: ios json nsurlconnection afnetworking-2

我在将json发布到url时收到此错误:

 Invalid top-level type in JSON write'

我甚至使用afnetworking post request code发送完美的JSON但是它一直给我错误。

我的代码:

NSString *  serviceType = @"xyz";
NSString *  remarks =@"project deadline is near ";
NSString *  emailId = @"xyx.live.com";


NSDictionary *params =
@ {
    @"serviceType" :serviceType,
    @"remarks" :remarks,
    @"emailId" :emailId

};

NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params
                                                   options:0 
                                                     error:&error];


NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];



AFHTTPRequestOperationManager *manager2 = [AFHTTPRequestOperationManager manager];
AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
[serializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[serializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
manager2.requestSerializer = serializer;



[manager2 POST:@"http://xyx.com" parameters:jsonString success:^(AFHTTPRequestOperation *operation, id responseObject) {
     NSLog(@"JSON_post_fzzlogin: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {



    //here is place for code executed in success case
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error while sending POST"
                                                        message:@"Sorry, try again."
                                                       delegate:nil
                                              cancelButtonTitle:@"Ok"
                                              otherButtonTitles:nil];
    [alertView show];

    NSLog(@"Error: %@", error);

}];

请帮我解决这个问题。提前谢谢

2 个答案:

答案 0 :(得分:1)

您尝试对请求进行两次编码,因为您为AFHTTPRequestOperationManager设置了请求序列化程序,并将参数作为编码的JSON字符串提供。因此,如果要使用请求序列化程序或不使用它并手动编码为JSON,则需要提供原始参数。

答案 1 :(得分:1)

这是您通过NSDictionary

发布JSON或AFNetworking的方式
NSDictionary *dict = @{@"Key":@"Value"};
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:[Util urlAppend:kListOfArticleCatagory] parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {

NSDictionary *responseObj = (NSDictionary *)responseObject;//casting to NSDictionary from id
NSLog(@"%@",responseObj);

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Something went wrong :%@",operation.responseString);

}];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
}

你不要通过AFNetworking发布JSON,而不是NSDictionary作为参数,它会在发布时转换为JSON。