Objective c 解析不同json字符串的正确条件
我正在为用户身份验证系统解析json 如果登录成功,服务器将发送以下用户对象Objective c 解析不同json字符串的正确条件,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
{
"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": "admin@8repz.com",
"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()
语句来解析和显示响应?你知道这是一个无效的json,对吗?我在发帖之前验证了它。json的根可以是字典或数组。你知道这是一个无效的json,是吗?我在发帖前验证了它。JSON的根可以是字典或数组。我喜欢这个结果。这比我使用嵌套if语句的方法更简洁。我喜欢这个结果。它比我使用嵌套if语句的方法更简洁。
//IF RESPONSE IS SIMPLY A STRING OBJECT FOR INVALID STRING, YOU HAVE BAD DATA
if(![results isEqualToString:@"Invalid Email or Password."]){
if([results objectForKey:@"users"]){ //Check to ensure users object exists
//You're good
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"]];
}
}else{
//Handle error
}
//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 {
}