0

I'm initiating a URL connection and my script is returning the following JSON:

( 1, { "id" = <-ID Here->; hash = <-Hash Here->; }, ( ), ( ) )

All the examples I've seen so far seem to have "ids" or identifiers before respective arrays/dictionaries. Despite searching around, I couldn't find a way to parse this. (i.e. I need to get the first boolean value, the id, the hash, and then the arrays as well (which are empty as of now)).

Sorry if I'm missing something-- I'm new to parsing JSON in Obj-C.Thanks for the help.

2 Answers 2

2

The feature I use is built in with the Cocoa libraries: the NSJSONSerialization class. It provides methods for parsing JSON into a graph, and encoding a graph into JSON. The rules are similar to plists (i.e. basic types plus arrays and dictionaries).

If you have NSData (which you can easily get from a string), you do like this:

NSArray *yourJSONAsObjectGraph = [NSJSONSerialization JSONObjectWithData:yourNSData options:nil error:&err];

Then, with your data above, objectAtIndex:0 would be an NSNumber that you can call boolValue on, objectAtIndex:1 will be an NSDictionary that you can call objectForKey:@"id" (and @"hash"), etc.

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

2 Comments

Thanks, this is useful. I'll try it out now and let you know.
The only caveat is that you need to know (or detect) what type of object the top-level will be. Usually you know because you are talking to your own API, but you can also detect. It will always be either an NSArray or NSDictionary (unless there is an error).
0

See How to use JSON in Objective-C. If you didn't hear about it yet, have a look at SBJSON.

4 Comments

I thought there was a native JSON parser in iOS development now. Am I wrong?
What to you mean by "native"? SBJSON is native. It's pure Objective-C. It's not made by Apple though.
See @ctrahey 's answer...it seems that way I don't have to use anything that's not built in with the default libraries.
@Kgrover - NSJSONSerialization is the Apple provided class you are thinking of

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.