Search code examples
objective-cjsonrestafnetworking-2url-encoding

AFNetworking GET parameters with JSON (NSDictionary) string contained in URL key parameter


This JSON string has to be sent:

{
"dashboard": "compact",
"theme": "dark",
"show_side_bar": "yes"
}

to a REST API using GET method in this format (since server retrieves data with this PHP code $_GET["setting"]) with AFHTTPRequestOperationManager, such that the equivalent URL becomes:

http://www.examplesite.com/api/change_setting?setting={ "dashboard" : "compact", "theme" : "dark", "show_side_bar" : "yes" }

When I create an NSDictionary of parameters in AFHTTPRequestOperationManager's GET:parameters:success:failure: which adds the url key parameter to the parameter dictionary itself like this:

{
  "setting": {
    "dashboard": "compact",
    "theme": "dark",
    "show_side_bar": "yes"
  }
}

In short only the JSON string must be encapsulated in setting parameter NOT as object of setting in a JSON string.

Edit: Here's the code:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{
                             kSettingDashboard: @"compact",
                             kSettingTheme: @"dark",
                             kSettingShowSideBar: @"yes"
                             };

[manager GET:kURLChangeSetting
  parameters:[NSDictionary dictionaryWithObject:parameters forKey:@"setting"]
     success:^(AFHTTPRequestOperation *operation, id responseObject) {
         // code
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         /// code
     }];

Solution

  • Try this:

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
    NSString *parametersString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    [manager GET:kURLChangeSetting
      parameters:@{@"setting" : parametersString}
         success:^(AFHTTPRequestOperation *operation, id responseObject) {
             // code
         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             /// code
         }];