Other answers work fine if the values ββare strings, however, if the values ββare dictionaries or arrays, this code will handle this.
It's important to note that there is no standard way to pass an array / dictionary along a query string, but PHP handles this output just fine
-(NSString *)serializeParams:(NSDictionary *)params { NSMutableArray* pairs = [NSMutableArray array]; for (NSString* key in [params keyEnumerator]) { id value = [params objectForKey:key]; if ([value isKindOfClass:[NSDictionary class]]) { for (NSString *subKey in value) { NSString* escaped_value = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[value objectForKey:subKey], NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8); [pairs addObject:[NSString stringWithFormat:@"%@[%@]=%@", key, subKey, escaped_value]]; } } else if ([value isKindOfClass:[NSArray class]]) { for (NSString *subValue in value) { NSString* escaped_value = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)subValue, NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8); [pairs addObject:[NSString stringWithFormat:@"%@[]=%@", key, escaped_value]]; } } else { NSString* escaped_value = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)[params objectForKey:key], NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8); [pairs addObject:[NSString stringWithFormat:@"%@=%@", key, escaped_value]]; [escaped_value release]; } } return [pairs componentsJoinedByString:@"&"]; }
<strong> Examples
[foo] => bar [translations] => { [one] => uno [two] => dos [three] => tres }
Foo = bar & translations [one] = UNO & translations [two] = dos & translations [three] = Tres
[foo] => bar [translations] => { uno dos tres }
Foo = bar & translations [] = UNO & translations [] = dos & translations [] = Tres
AlBeebe Oct 22 '12 at 19:16 2012-10-22 19:16
source share