NSString manipulation
I have an NSString which I need to 'clean' before feeding it into my json read however I can't find a way of doing so.
This is my NSString:
"DUMMY({parameters:{code:"60246", language:"en", country:"en"}, result:{"...JSON...});"
Basically I need to remove everything except: {"...JSON...}
The problem is the codes etc开发者_JS百科 change?
If the string is at least consistently built in the format you gave, you could use this:
NSUInteger rangeStart = [string rangeOfString:@"result:"].location;
NSUInteger lastBrace = [string rangeOfString:@"}" options:NSBackwardsSearch].location;
NSUInteger jsonStart = rangeStart + [@"result:" length];
NSUInteger jsonLength = lastBrace - jsonStart + 1;
NSRange jsonRange = NSMakeRange(jsonStart, jsonLength);
NSString *justJson = [string substringWithRange:jsonRange];
Here's a slightly more concise, but perhaps less efficient, method:
NSUInteger rangeStart = [string rangeOfString:@"result:"].location;
NSString *justJson = [string substringFromIndex:rangeStart + [@"range:" length]];
NSUInteger lastBrace = [justJson rangeOfString:@"}" options:NSBackwardsSearch].location;
justJson = [justJson substringToIndex:lastBrace+1];
Why don't you convert into NSDictionary and then fetch only the element with "result" key? For example you can use JSONFramework and do something like this:
NSDictionary* dic = [yourJsonEncodedStrin JSONValue];
id result = [dic objectForKey:@"result"];
You can convert back to a string using:
NSString* resultString = [result JSONRepresentation];
精彩评论