简体   繁体   English

如何使用目标c在iOS中解析jsonstring?

[英]How to parse jsonstring in iOS using objective c?

I have the following json, 我有以下json,

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

I'm using following code to parse it, 我正在使用以下代码进行解析,

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

I'm able to get the value for the key data but I'm not be able to get the value of username and password. 我可以获取密钥数据的值,但是无法获取用户名和密码的值。 How to get those values? 如何获得这些价值?

change 更改

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

to

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

then 然后

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

if json is in respose data then 如果json位于重新放置数据中,则

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

if json is in string then 如果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"];

您可以通过credentials[@"username"]credentials[@"password"]获得这些值。

do like 喜欢

reason it deverives like nested Dictionry 它像嵌套Dictionry一样Dictionry原因

NSString* loginMethod= json[@"method"]; // this is correct

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

Choice -2 选择-2

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM