views:

44

answers:

2

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 change?

+1  A: 

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];
Luca Bernardi
+2  A: 

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];
mipadi
the first one removes everything except the first : after result?
TheLearner
Sorry, used the string "range" in the example instead of "result". Had `NSRange` on my brain and got it mixed up. :)
mipadi
not sure what you mean but the first snippet of code leaves a lonely : color before the json
TheLearner
@TheLearner, try my answer, it should work perfectly.
Jacob Relkin
@TheLearner: I just ran a test, and it worked (according to your specs). Here's a sample: http://gist.github.com/591836
mipadi
@mipadi - my apologies I misunderstood what you were saying. Thank you very much it works perfectly!
TheLearner