[转]将a=1&b=2&c=3 格式字符串转换成

2016-06-07  本文已影响663人  祖冲之

最近在做支付宝支付,返回值里的一些参数是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];

原文链接 

上一篇下一篇

猜你喜欢

热点阅读