这是我执行的代码......
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&error];
[[NSUserDefaults standardUserDefaults] setObject:[dictionary objectForKey:@"user_id"] forKey:@"User_Id"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"User_Id"]);
这是我的 Json Response
{
"flag": "true",
"message": "success",
"data": [
{
"username": "ankurk",
"user_id": "16",
"email": "ankurk.psk@gmail.com"
}
]
}
但我坚持将用户ID存储到用户默认值 请帮助我在这里发生什么事?
谢谢
答案 0 :(得分:2)
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&error];
NSArray *array = [dictionary objectForKey:"data"];
NSDictionary *dataDictionary=[array objectAtIndex:0];
[[NSUserDefaults standardUserDefaults] setObject:[dataDictionary objectForKey:@"user_id"] forKey:@"User_Id"];
[[NSUserDefaults standardUserDefaults] synchronize];
答案 1 :(得分:1)
根JSON对象没有与键“user_id”关联的值,因为“user_id”位于“data”数组中。您需要首先从JSON对象中提取“data”数组,然后检索与“user_id”键关联的值。请尝试使用以下代码段将“user_id”值存储到NSUserDefaults
。
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&error];
NSArray *dataArray = [dictionary objectForKey:"data"];
[[NSUserDefaults standardUserDefaults] setObject:dataArray[@"user_id"] forKey:@"User_Id"];
答案 2 :(得分:1)
{{1}}