NSJSONSerialization for an object with an id attribute

前端 未结 2 1821
执笔经年
执笔经年 2021-01-24 11:19

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 pars

相关标签:
2条回答
  • 2021-01-24 11:24

    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);
        return;
    }
    NSString *identifier = dictionary[@"id"];
    NSString *name = dictionary[@"name"];
    
    0 讨论(0)
  • 2021-01-24 11:48

    If you passed

    {
        id: 123,
        name: "Chris"
    }
    

    to NSJSONSerialization as an NSData object you would get an NSDictionary with two keys that are NSString's with the value @"id" and @"name", at that point you can take the value from the id key and pass it to an attribute on your Objective-C model that is named something other than id. An example being recordId

    0 讨论(0)
提交回复
热议问题