将其分解为可用字符串的最佳方法是什么?

时间:2014-03-24 20:20:06

标签: ios arrays nsstring

什么是最好的解析方法?

字符串:      UMversion=2.9&UMstatus=Approved&UMauthCode=152058&UMrefNum=59567592&UMavsResult=Address%3A%20Match%20%26%205%20Digit%20Zip%3A%20Match&UMavsResultCode=YYY&UMcvv2Result=Match&UMcvv2ResultCode=M&UMresult=A&UMvpasResultCode=&UMerror=Approved&UMerrorcode=00000&UMcustnum=&UMbatch=1&UMbatchRefNum=91016&UMisDuplicate=N&UMconvertedAmount=&UMconvertedAmountCurrency=840&UMconversionRate=&UMcustReceiptResult=No%20Receipt%20Sent&UMprocRefNum=&UMcardLevelResult=A&UMauthAmount=10&UMfiller=filled

我从Web服务中将其作为一个很长的字符串。列出每个变量然后他们有a = sign然后我需要用变量填充变量。

我需要将所有这些数据都放入变量中进行检查。

那么,我应该如何分解它。

2 个答案:

答案 0 :(得分:2)

使用这种代码:

NSArray* components = [veryLongString componentsSeparatedByString:@"&"]; // array of strings like "x=y"
NSMutableDictionary* parsedResult = [NSMutableDictionary new];
for (NSString* keyValuePair in components) {
  NSArray* keyAndValue = [keyValuePair componentsSeparatedByString:@"="];
  NSString* key = keyAndValue[0];
  NSString* value = (keyAndValue.count>1) ? keyAndValue[1] : nil;
  // remove percent escapes in case we have URL-encoded characters in the value like '%20' and the like
  parsedResult[key] = [value stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding] ?: [NSNull null];
}

NSLog(@"dictionary of parameters: %@", parsedResult);

您最终会得到一个字典,其中包含从字符串中提取的键和值。

答案 1 :(得分:-1)

NSString* firstPass = [sourceString stringByReplacingOccurrencesOfString:@"&" withString:@"\",\""];
NSString* secondPass = [firstPass stringByReplacingOccurrencesOfString:@"=" withString:@"\":\""];
NSString* grandFinale = [NSString stringWithFormat:@"{\"%@\"}"];
NSData* jsonSource = [grandFinale dataUsingEncoding:NSUTF8Encoding];
NSError* error = nil;
NSDictionary* theBiggie = [NSJSONSerialization JSONObjectWithData:jsonSource options:0 error:&error];

我认为NSJSONSerialization会自动修复百分比编码。如果没有,请通过grandFinale运行stringByRemovingPercentEncoding