Cristiano Cristiano - 1 year ago 90
Objective-C Question

NSJSONSerialization for an object with an id attribute

So I'm trying to do a GET request that returns some Json. The json that gets returned from this request has an id attribute, so the class that I use NSJSONSerialization to parse the json should have an id attribute. Since id is reserved in objective-c, I can't include it as an attribute in my class. Basically, my question boils down to what should I do to make sure the id attribute gets parsed correctly into an object of my class.

Rob Rob
Answer Source

Yes, id is a reserved keyword (although, as Josh points out, you could use it as a variable name, he's quite right that's a bad idea), but it can still be used as a key in a NSDictionary. For example, if your JSON looks like:

{ "id" : "23432423", "name" : "Jason Boggess" }

You can then parse it as follows:

NSError *error = nil;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (error) {
    NSLog(@"%s: JSONObjectWithData error: %@", __FUNCTION__, error);
NSString *identifier = dictionary[@"id"];
NSString *name = dictionary[@"name"];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download