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

标签 ios objective-c json boolean

我有a small iPhone app ,它从社交网络中获取用户信息(姓名、城市、性别),然后将其显示在 View 中:

app screenshot

数据以 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;
    }
)

然后我将其打印在我的 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

我解析 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"];

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

我已经尝试了以下但没有成功:

         _user.female    = !(BOOL)dict[@"sex"];
         _user.female    = (0 != dict[@"sex"]);
         _user.female    = (int)dict[@"sex"];

谁能告诉我,如何在此处正确地将 id 转换为 BOOL

最佳答案

您不能将对象转换为 Objective C 中的原语(id 是对象指针)。假设您的 JSON 解析器将数字解析为 NSNumbers,您只需要这样做:

![dict[@"sex"] boolValue]

关于ios - 将 JSON 中的 "sex = 0"转换为 BOOL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21293353/

相关文章:

ios - 无法在iOS中压缩来自ALASSET URL的视频?

javascript - React - 检查 Prop

json - jq 按日期过滤json

ios - 以编程方式清除 iOS 上的 DNS 缓存

ios - 像 The Magazine 那样滑动 UIViews

ios - UIPopoverController 中具有动态高度的 UITableView

ios - 处理同一帐户下多个应用程序的身份验证 - iOS

objective-c - "calling queue"是什么?

java - 从提供空数据的 Struts2 操作返回 JSON 对象

ios - 从 UITapGestureRecognizer 获取对象的标签