15

I have a JSON string as an NSString object in iOS. I want to parse this and pull out the given parameters in the JSON string. Is there a efficient way to parse this or is the only way to search for substrings etc.?

2 Answers 2

50

The way to do it with iOS 5 is to use the NSJSONSerialization class. You will want to first convert your string to an NSData object, and call the class method JSONObjectWithData

NSData *jsonData = [myJsonString dataUsingEncoding:NSUTF8StringEncoding]; NSError *e; NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:nil error:&e]; 

Note that JSONObjectWithData will return either an NSDictionary or an NSArray, depending whether your JSON string represents an a dictionary or an array.

Sign up to request clarification or add additional context in comments.

1 Comment

Notice that you should use 0 or NSJSONReadingMutableContainers for the options to suppress the compiler warning.
0

A good framework for converting JSON strings to Objective-C objects (NSArray and NSDictionary) is SBJson (Github).

Usage:

NSDictionary *dict = [myJsonString JSONValue]; 

3 Comments

Is there a way to do it with iOS 5 JSON?
Yes, but it is more involved and limits your application to running only on iOS 5.
I agree, SBJSON is your friend. Much more convenient than the official API, and works with older iOS versions too.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.