如何使用Objective c解析iOS中的jsonstring?

时间:2016-02-12 06:34:12

标签: ios objective-c json

我有以下json,

{   
    "method":"login", 
    "data":{  
        "username":"abc", 
        "password":"123" 
    } 
} 

我正在使用以下代码来解析它,

NSString* loginMethod= json[@"method"];
NSString* credentials= json[@"data"];
NSLog(@"credentials %@",credentials);

我能够获取密钥数据的值,但我无法获得用户名和密码的值。如何获得这些价值观?

4 个答案:

答案 0 :(得分:2)

变化

NSString* credentials= json[@"data"];

NSDictionary* credentials= json[@"data"];

然后

NSString *username = credentials[@"username"];

答案 1 :(得分:1)

您可以按credentials[@"username"]credentials[@"password"]获取这些值。

答案 2 :(得分:1)

喜欢

它会像嵌套Dictionry

那样失真
NSString* loginMethod= json[@"method"]; // this is correct

NSString* username= json[@"data"][@"username"];
NSString* password= json[@"data"][@"password"];

选择-2

 NSString* loginMethod= json[@"method"]; 

// This isNested Dictionary so Do like
NSDictionary* temp= json[@"data"];
NSString *username = temp[@"username"];
NSString * password = temp[@"password"];

答案 3 :(得分:1)

如果json处于respose数据中,那么

NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:request.responseData options:kNilOptions error:&err];

如果json是字符串,那么

NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding]; options:kNilOptions error:&err];


NSString* loginMethod= [jsonDic objectForKey:@"method"];

NSString* usename= [[jsonDic objectForKey:@"data"]objectForKey:@"username"];
NSString* password= [[jsonDic objectForKey:@"data"]objectForKey:@"password"];