[转]将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];

原文链接 

你可能感兴趣的:([转]将a=1&b=2&c=3 格式字符串转换成字典(解析地址里面各参数值)