开发者

How can I parse this string using NSString?

开发者 https://www.devze.com 2023-02-04 11:45 出处:网络
I have the following string: callback({\"Outcome\":\"Success\", \"Message\":null, \"Identity\":\"Request\", \"Delay\":0.002, \"Symbol\":\"AAPL\", \"CompanyName\":\"Apple I开发者_如何学JAVAnc.\", \"Da

I have the following string:

callback({"Outcome":"Success", "Message":null, "Identity":"Request", "Delay":0.002, "Symbol":"AAPL", "CompanyName":"Apple I开发者_如何学JAVAnc.", "Date":"1\/13\/2011", "Time":"4:02:36 PM", "Open":344.6, "Close":345.93, "PreviousClose":344.42, "High":346.63, "Low":343.86, "Last":345.93, "Change":1.51, "PercentChange":0.438, "Volume":785960})

I want my final string to not contain callback( and the the last ) at the end of the string. How can I modify this NSString?


NSScanner is a good fit for this sort of thing.

NSString *json = nil;
NSScanner *scanner = [NSScanner scannerWithString:fullString];
[scanner scanUpToString:@"{" intoString:NULL]; // Scan to where the JSON begins
[scanner scanUpToString:@")" intoString:&json];

NSLog(@"json = %@", json);


Make an NSMutableString out of it, called string. i.e. NSMutableString *string = [NSMutableString stringWithString:myString];.

Then do string = [string substringToIndex:[string length]-1]; and then string = [string substringFromIndex:9]; or some such.

Or, again create an NSMutableString instance with your NSString instance, and call [string replaceOccurrencesOfString:@"callback(" withString:@"" options:NSLiteralSearch range:NSMakeRange(0, [string length])]; and [string replaceOccurrencesOfString:@")" withString:@"" options:NSLiteralSearch range:NSMakeRange(0, [string length])];. This might be preferred.

Either way, then create an NSString instance with the new string, something like goodString = [NSString stringWithString:string]; if you need an NSString out of this.


You can't modify an NSString (only an NSMutableString), but you can use [string substringWithRange:NSMakeRange(9, [string length] - 10)]. To actually mutate an NSMutableString, you'd have to use two deleteCharactersInRange: calls to trim the parts you don't want.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号