JSON (JavaScript Object Notation) is a lightweight data-interchange format. This framework contains a collection of categories adding full JSON support to Cocoa by extending existing Objective-C classes. This site documents version __VERSION__ of the framework.
Linking to the JSON framework and
importing the <JSON/JSON.h>
header provides the
following main methods.
The following methods are added as a category on NSArray and NSDictionary:
- (NSString *)JSONRepresentation;
- (NSString *)JSONRepresentationWithOptions:(NSDictionary *)opts;
The following methods are added as a category on NSString.
- (id)JSONValue;
- (id)JSONValueWithOptions:(NSDictionary *)opts;
Strictly speaking JSON must have exactly one top-level container. (Either an array or an object.) Bare nulls, numbers, booleans and strings are not valid JSON on their own. It can be quite convenient to pretend that such fragments are valid JSON however. The following methods will let you do so:
- (NSString *)JSONFragment;
- (id)JSONFragmentValue;
Here's how the distinct JSON types map to Objective-C types.
Object <=> NSDictionary
Array <=> NSArray
String <=> NSString
Null <=> NSNull
Boolean <=> NSNumber
Number <= NSNumber
Number => NSDecimalNumber
This framework is limited to parsing strict JSON. (Other than the above mentioned support for JSON fragments.) For example, it does not support trailing commas in arrays or objects.
I strongly believe in correctness first, speed later and that was very much the angle of attack when creating this framework. Then out of the blue Jens Alfke emailed me a couple of patches providing a serious performance boost. I've made sure to keep up this performance in any later changes.
Below are some performance measurements comparing this framework to Blake Seely's BSJSONAdditions. These are the same strings that Marc Lehmann used comparing JSON::XS to its competitors. These measurements were taken with the revision r3210 of trunk.
short string | long string (~12k) | |||
---|---|---|---|---|
encode | decode | encode | decode | |
BSJSONAdditions | 10488.8 | 4134.0 | 70.5 | 3.7 |
SBJSON | 39858.1 | 23319.8 | 714.3 | 555.8 |
In BSJSONAdditions' defence, its parser allows you to embed C-style comments in the JSON text. This can be very handy for configuration files, for example, but makes the parser a little more complicated. SBJSON does not support them as they are not part of the JSON spec.
Currently none known. If you find one, feel free to report it via email.
Cocoa JSON Framework is written by yours truly, Stig Brautaset, and released under the revised BSD license. You are welcome to email me.
http://code.brautaset.org lists more code by me. I occasionally announce new projects on my blog. It also contains the definite list of ways to contact me.