[转]将a=1&b=2&c=3 格式字符串转换成
最近在做支付宝支付,返回值里的一些参数是a=1&b=2&c=3 格式字符串
不方便使用 于是找到了这个方法
- (NSDictionary*)dictionaryFromQuery:(NSString*)query usingEncoding:(NSStringEncoding)encoding {
NSCharacterSet* delimiterSet = [NSCharacterSetcharacterSetWithCharactersInString:@"&;"];
NSMutableDictionary* pairs = [NSMutableDictionarydictionary];
NSScanner* scanner = [[NSScanneralloc]initWithString:query];
while(![scannerisAtEnd]) {
NSString* pairString =nil;
[scannerscanUpToCharactersFromSet:delimiterSetintoString:&pairString];
[scannerscanCharactersFromSet:delimiterSetintoString:NULL];
NSArray* kvPair = [pairStringcomponentsSeparatedByString:@"="];
if(kvPair.count==2) {
NSString* key = [[kvPairobjectAtIndex:0]
stringByReplacingPercentEscapesUsingEncoding:encoding];
NSString* value = [[kvPairobjectAtIndex:1]
stringByReplacingPercentEscapesUsingEncoding:encoding];
[pairssetObject:valueforKey:key];
}
}
return[NSDictionarydictionaryWithDictionary:pairs];
}