将JSON中的"sex = 0"转换为BOOL

Ale*_*ber 0 json boolean objective-c ios

我有一个小型iPhone应用程序,它从社交网络中获取用户信息(名称,城市,性别),然后在视图中显示:

应用截图

数据以JSON格式到达(请注意sex = 0男性用户):

2014-01-22 21:18:42.915 oauthMailru[697:1303] json=(
        {
        age = 41;
        "app_installed" = 1;
        birthday = "08.06.1972";
        "first_name" = Alexander;
        "friends_count" = 17;
        "has_pic" = 1;
        "is_friend" = 0;
        "is_online" = 0;
        "is_verified" = 1;
        "last_name" = Farber;
        "last_visit" = 1390312557;
        link = "http://my.mail.ru/mail/farber72/";
        location =         {
            city =             {
                id = 855;
                name = "Dusseldorf";
            };
            country =             {
                id = 46;
                name = "Germany";
            };
        };
        nick = "Alexander Farber";
        pic = "http://avt.appsmail.ru/mail/farber72/_avatar";
        "pic_big" = "http://avt.appsmail.ru/mail/farber72/_avatarbig";
        "pic_small" = "http://avt.appsmail.ru/mail/farber72/_avatarsmall";
        "referer_id" = "";
        "referer_type" = "";
        sex = 0;
        "show_age" = 1;
        uid = 17880121030128875114;
        vip = 0;
    }
)
Run Code Online (Sandbox Code Playgroud)

然后我在DetailViewController.m中打印它:

2014-01-22 21:18:42.920 oauthMailru[697:70b] id: 17880121030128875114
2014-01-22 21:18:42.920 oauthMailru[697:70b] first_name: Alexander
2014-01-22 21:18:42.921 oauthMailru[697:70b] last_name: Farber
2014-01-22 21:18:42.921 oauthMailru[697:70b] city: Dusseldorf
2014-01-22 21:18:42.921 oauthMailru[697:70b] female: 1
2014-01-22 21:18:42.922 oauthMailru[697:70b] avatar: http://avt.appsmail.ru/mail/farber72/_avatarbig
Run Code Online (Sandbox Code Playgroud)

解析JSON输入的代码在ViewController.m中,并将其分配给User.h属性:

         NSDictionary *dict = json[0];

         _user = [[User alloc] init];
         _user.userId    = dict[@"uid"];
         _user.firstName = dict[@"first_name"];
         _user.lastName  = dict[@"last_name"];
         _user.city      = dict[@"location"][@"city"][@"name"];
         _user.avatar    = dict[@"pic_big"];
         _user.female    = !(BOOL)dict[@"sex"];
Run Code Online (Sandbox Code Playgroud)

由于某种原因,最后一个用户属性 - BOOL female总是对我设置错误.

我试过以下但没有成功:

         _user.female    = !(BOOL)dict[@"sex"];
         _user.female    = (0 != dict[@"sex"]);
         _user.female    = (int)dict[@"sex"];
Run Code Online (Sandbox Code Playgroud)

任何人都可以建议,如何正确地投入idBOOL这里?

Lan*_*nce 6

您不能在Objective C中将对象转换为基元(ids是对象指针).假设您的JSON解析器将数字解析为NSNumbers,您只需执行以下操作:

![dict[@"sex"] boolValue]
Run Code Online (Sandbox Code Playgroud)

  • @AlexanderFarber:如果有疑问,请将计算分成不同的步骤:`NSNumber*val = dict [@"sex"]; BOOL b = [val boolValue]; _user.female =!b;`.设置断点并检查每个变量. (2认同)