Objective C: how to convert nested NSDictionarys and NSArrays to URLEncoded string

Deadly 提交于 2019-12-12 00:32:13

问题


I have a Symfony2 project serving both a JQuery Web client and an Objective C iPhone APP.

JQuery sends properly its urlencoded data to the server. Data that is properly accessed in the Symfony2 Controller using $this->getRequest()->get('myKey');.

Therefor, data is sent in application/x-www-form-urlencoded.

In order not to change my Symfony Controllers (that happens to be the the whole API of my system and has around 200 AJAX calls in the form I described before), I'd like the Objective C to send the data exactly in the same way.

I have it partially gotten. I mean, I know how to convert a simple NSDictionary to a URI parameters format. This would be the code (Thanks to Michael Sivolobov).

NSMutableArray* parametersArray = [[[NSMutableArray alloc] init] autorelease];
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
    [parametersArray addObject:[NSString stringWithFormat:@"%@=%@", key, obj]];
}];
NSString* parameterString = [parametersArray componentsJoinedByString:@"&"];

But my problem know is to know how to convert in a similar way some more complex data. Such as nested NSArrays and NSDictionarys (very usual when working with JSON). Anybody knows any method to convert such data to URL (key1=value1&key2=value2, etc...) in Objective C??

EDIT: example of the data I'd need to send by url.

NSArray *myArray = [NSArray arrayWithObjects: @"Value2", @"Value3", nil];
NSDictionary *myDict = [NSDictionary dictionaryWithObjectsAndKeys: @"Value1", @"key1", myArray, @"Value2"];

Something that in JSON would be {"key1": "value1", "key2": ["value2", "value3"]}

What is the best way in Objective C to get that structure and convert it to URLencode before passing it to the Http POST? I thought there would be some JSON or Cocoa method... but there is nothing...


回答1:


Holy Cow! I had to dust off some really old PHP knowledge for this: http_build_query().

The format of a complex mixed dictionary/array objects is base[key][key]…[key]=value

For the JSON {"key1": "value1", "key2": ["value2", "value3"]}, PHP would expect key1=value1&key2[0]=value3&key2[1]=value3 as a URL encoded string (so key1=value1&key2%5B0%5D=value3&key2%5B1%5D=value3).


For a more complex example: {"x": {"y": ["a", "b"]}, "z" : "c"}, PHP would expect x[y][0]=a&x[y][1]=b&z=c.



来源:https://stackoverflow.com/questions/17166931/objective-c-how-to-convert-nested-nsdictionarys-and-nsarrays-to-urlencoded-stri

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!