objective-c - iOS解析不同json字符串的正确条件

标签 objective-c ios json

我正在为用户身份验证系统解析 json。

如果登录成功,服务器将发送以下用户对象;

{

    "users": {
        "id": "1",
        "FB_first_name": null,
        "FB_last_name": null,
        "FB_gender": null,
        "FB_id": null,
        "FB_link": null,
        "FB_locale": null,
        "FB_name": null,
        "FB_username": null,
        "created_at": "2011-01-02 08:30:59 UTC",
        "updated_at": "2011-01-02 08:31:23 UTC",
        "email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9ffefbf2f6f1dfa7edfaefe5b1fcf0f2" rel="noreferrer noopener nofollow">[email protected]</a>",
        "language_id": "1"
    }

}

我使用以下代码解析它;

    NSDictionary *userDic = (NSDictionary*)[(NSDictionary*)results objectForKey:@"users"];

    User *aUser = [[User alloc] initWithID:[userDic objectForKey:@"id"]
                              withUserName:[userDic objectForKey:@"FB_name"]
                             withUserEmail:[userDic objectForKey:@"email"]
                             withUserFName:[userDic objectForKey:@"FB_first_name"]];

但是如果用户无效,服务器会发送以下响应;

[

    "Invalid Email or Password."

]

我应该使用什么 if() 语句来解析和显示这两种情况下的响应?

最佳答案

//parse out the json data
NSError* error;
id json = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
if ([json isKindOfClass:[NSArray class]){
    //You have to be sure that on error it returns array not a dictionary
    NSArray *arr = (NSArray*)json;
    NSString *errorMsg = [arr objectAtIndex:0];
}
else {

}

关于objective-c - iOS解析不同json字符串的正确条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13821470/

相关文章:

ios - 仅使用键值存储检测 iCloud 帐户可用性/更改?

ios - 快速将数组转换为 JSON 字符串

ios - 使用 Realm 移动平台透明登录

java - Volley jsonArray 传递

javascript - AJAX获取JSON函数不循环

objective-c - 带有可见控件的透明 NSWindow

ios - 对属性和 ivars 感到困惑

javascript - 构造嵌套转义 JSON 字符串以进行 JSON.parse() 递归检索

objective-c - 什么机制检测未分配内存的访问?

ios - 在模拟器上测试使用 Web 服务器的 iOS 应用程序