具有ID属性的对象的NSJSONSerialization [英] NSJSONSerialization for an object with an id attribute

查看:69
本文介绍了具有ID属性的对象的NSJSONSerialization的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在尝试执行一个返回一些Json的GET请求.从此请求返回的json具有id属性,因此我使用NSJSONSerialization解析json的类应具有id属性.由于id是在Objective-c中保留的,因此我不能将其作为属性包含在类中.基本上,我的问题归结为该怎么做,以确保将id属性正确解析为类的对象.

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.

推荐答案

是的,id是保留关键字(尽管,正如乔什指出,您可以将其用作变量名,他说的很对,这是个坏主意),但是它仍然可以用作NSDictionary中的键.例如,如果您的JSON看起来像:

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"];

这篇关于具有ID属性的对象的NSJSONSerialization的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆