如何从iOS中的字典中获取值 [英] How to get values from a dictionary in iOS
问题描述
我是 iOS 的新手。我创建了一个登录页面,一切正常。我使用 JSON 来检查用户名和密码,并以字典格式从服务器获得响应。我想从字典中提取值并在我的程序中检查它们。
我从服务器得到的回复是:
I am new to iOS. I created a login page and everything works fine. I used JSON for checking username and password and got the response from server in a dictionary format. I want to extract the values from the dictionary and check them in my program. The response which I get from the server is:
json: {
error = 0;
msg = "";
value = {
user = false;
};
};
首先,我想检查带有 键的值是否有错误
0
或 1
的。然后我想用密钥 user
检查值。我不知道应该如何编码来检查它。有人可以帮忙吗?
First I want to check if the value with the key error
is 0
or 1
. Then I want to check the value with the key user
. I don't know how I should code to check it. Can anyone help?
我试过的代码如下:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *respString = [[NSString alloc] initWithData:loginJSONData encoding:NSUTF8StringEncoding];
SBJsonParser *objSBJSONParser = [[SBJsonParser alloc] init];
NSDictionary *json = [[NSDictionary alloc] initWithDictionary:[objSBJsonParser objectWithString:respString]];
NSLog(@"json: %@",json);
NSString *error = [json objectForKey:@"error"];
NSLog(@"error: %@", error);
if ([error isEqualToString:@"o"])
{
NSLog(@"login successful");
}
else
{
NSLog(@"login fail");
}
}
推荐答案
使用现代的Objective-C,访问数组和字典中的东西变得更容易。
Using modern Objective-C, accessing things in arrays and dictionaries become easier.
你应该使用以下语法:
ID< NSObject的> value =字典[@key];
同样,
ID< NSObject的> value = array [1]; // 1是索引
将上述内容应用于问题:
Applying the above to the question:
NSString * error = json [@error];
NSDictionary * value = json [@value];
BOOL user = [json [@value] [@ user] boolValue];
如上所述,允许嵌套,但这不是一个好习惯。
As in the above line, nesting is allowed, but it is not a good practice.
这篇关于如何从iOS中的字典中获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!