1

I am using a web API and for example it returns:

access_token=aZDi8ZlmDL34YyxCQt0jXdsRl9Kcinye8r8ilwqCOe3-OII2B96XblSyK7urG4DvPYc&expires_in=1396212623&is_voice_enrolled=false&device_id=3

So, I need to split up this single string to Key/Value pairs.

access_token:aZDi8ZlmDL34YyxCQt0jXdsRl9Kcinye8r8ilwqCOe3-OII2B96XblSyK7urG4DvPYc

expires_in:1396212623

is_voice_enrolled:false

device_id:3

What is the best way to convert this? Should I split by the & and then split again by the = sign?

Thanks!

Alan
  • 9,331
  • 14
  • 52
  • 97
  • 1
    This is essentially the same question as the following (with the same solution): http://stackoverflow.com/questions/3997976/parse-nsurl-query-property – rmaddy Mar 04 '14 at 18:20

2 Answers2

4

Yep, split on & and then on =, like this:

NSString* data = @"access_token=aZDi8ZlmDL34YyxCQt0jXdsRl9Kcinye8r8ilwqCOe3-OII2B96XblSyK7urG4DvPYc&expires_in=1396212623&is_voice_enrolled=false&device_id=3";

NSMutableDictionary* result = [@{} mutableCopy];
[[data componentsSeparatedByString:@"&"] enumerateObjectsUsingBlock:^(NSString* obj, NSUInteger idx, BOOL *stop) {
    NSArray* components = [obj componentsSeparatedByString:@"="];
    result[components[0]] = components[1];
}];

NSLog(@"%@", result);
andreamazz
  • 4,256
  • 1
  • 20
  • 36
  • works great :) thank you for this. This seems more efficient than the way I would have written it. – Alan Mar 04 '14 at 19:09
2

Yes, split by the & and then by the =.

Merlevede
  • 8,140
  • 1
  • 24
  • 39