0

我是 ios 的初学者和我的一项活动:这是我的 nsstring,现在我想从这个字符串中获取“LocationId”但我有问题.....我尝试在数组中添加这个字符串,然后获取 LocationId但我也有错误....

Nsstring *Str={"UserName":"ankitdemo","UserId":"08f11980-9920-4127-8fe7-78e1c40f6002","RoleName":"Doctor","RoleId":"87b4193c-1252-4505-a81b-2b49b8db57f3","FirstName":"Ankit","MiddleName":"","LastName":"Gupta","LocationId":"5f15648f-12ef-4534-a145-4044bc7c742e"}


Nsstring  *LocationId=[NSString stringWithFormat:@"%@",[Str valueForKey:@"LocationId"]];

或者

 NSMutableArray *location =[[NSMutableArray alloc]init];
[location addObject:self.WebService.ptr];
 NSLog(@"location id is %@",location);

LocationId=[NSString stringWithFormat:@"%@",[[location objectAtIndex:0]valueForKey:@"LocationId"]];
NSLog(@"location id is %@",LocationId);

但我有错误....

ERROR
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason:  '[<__NSCFString 0x881d6d0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key LocationId.'
Solve this problem.......
4

4 回答 4

3

这样做

您必须使用 JSON 解析器...

 NSDictionary *location = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] 
                                                 options:NSJSONReadingMutableContainers
                                                   error: &e];
 NSLog(@"location id is %@",location);

LocationId=[NSString stringWithFormat:@"%@",[[location objectAtIndex:0]valueForKey:@"LocationId"]];
NSLog(@"location id is %@",LocationId);
于 2013-07-04T08:21:25.320 回答
2

您提供的代码有很多问题,我怀疑您是否正确复制和粘贴了它。例如Nsstring不会编译。

但是,一般而言,您从 JSON 字典之类的内容创建了一个字符串,但语法不正确。而且您正在尝试获取未在 NSString 上定义的属性的值,这是导致错误的原因。

你正在寻找这样的东西:

NSDictionary *dictionary = @{ @"UserName" : @"ankitdemo",
                              @"UserId" : @"08f11980-9920-4127-8fe7-78e1c40f6002",
                              @"RoleName" : @"Doctor",@
                              @"RoleId" : @"87b4193c-1252-4505-a81b-2b49b8db57f3",
                              @"FirstName" : @"Ankit",
                              @"MiddleName" :@"",
                              @"LastName" : @"Gupta",
                              @"LocationId" : @"5f15648f-12ef-4534-a145-4044bc7c742e" };

NSString *locationId = dictionary[@"LocationId"];
于 2013-07-04T08:22:15.513 回答
0

您提供的代码无法编译,但我猜您有一些 JSON 作为NSString

NSError *e;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] 
                                                     options:NSJSONReadingMutableContainers
                                                       error: &e];

if (!json)
    NSLog(@"Error: %@",e);
else 
    NSString *locationID = [json objectForKey:@"LocationId"];
于 2013-07-04T08:19:54.530 回答
0

当然你会得到 NSUnknownKeyException。NSString没有LocationId 访问器

如果要解析 JSON,请使用 JSON 解析器,例如NSJSONSerialization

valueForKey:哦,当你的意思是不要使用objectForKey:

于 2013-07-04T08:21:16.377 回答