2015-09-08 45 views
1

使用afnetworking我得到這個錯誤,而張貼的JSON到網址:無法投遞JSON在IOS

Invalid top-level type in JSON write' 

我使用afnetworking POST請求的代碼,甚至發送完美JSON但它不斷給我的錯誤。

我的代碼:

NSString * serviceType = @"xyz"; 
NSString * remarks [email protected]"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); 

}]; 

請幫我出這方面.thanks提前

回答

1

您正在嘗試,因爲你設置的請求串行的AFHTTPRequestOperationManager並提供參數編碼的JSON字符串編碼要求的兩倍。因此,如果您想使用請求序列化程序,或者不使用它並手動編碼爲JSON,則需要提供原始參數。

1

這是你如何發佈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作爲您發佈它,而NSDictionary