【问题标题】:Issue with SBJsonParserSBJsonParser 的问题
【发布时间】:2011-10-01 22:45:44
【问题描述】:

我的 iPhone 应用程序正在从我的网络服务接收这个 json 字符串:

{"res":true,"users":[{"id":"79","username":""},{"id":"81","username":""},{"id":"83","username":""},{"id":"80","username":""},{"id":"82","username":""}]}

我正在使用以下代码处理它:

SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
NSError *error = nil;

NSDictionary *dictionary = [jsonParser objectWithString:responseString error:&error];

其中responseString 是使用 JSON 接收的字符串。

现在,如果我检查 [[dictionary valueForKey:@"res"] boolValue] 它是正确的布尔值。 问题在于[dictionary objectForKey:@"users"] 我不明白它是什么类型的对象。

我也试试这个:

NSLog(@"Is of type NSString?: %@", ([[dictionary objectForKey:@"users"] isMemberOfClass:[NSString class]])? @"Yes" : @"No");
NSLog(@"Is of type NSArray?: %@", ([[dictionary objectForKey:@"users"] isMemberOfClass:[NSArray class]])? @"Yes" : @"No");
NSLog(@"Is of type NSMutableArray?: %@", ([[dictionary objectForKey:@"users"] isMemberOfClass:[NSMutableArray class]])? @"Yes" : @"No");
NSLog(@"Is of type NSDictionary?: %@", ([[dictionary objectForKey:@"users"] isMemberOfClass:[NSDictionary class]])? @"Yes" : @"No");
NSLog(@"Is of type NSMutableDictionary?: %@", ([[dictionary objectForKey:@"users"] isMemberOfClass:[NSMutableDictionary class]])? @"Yes" : @"No");

但它总是说No。

感谢您的帮助。

【问题讨论】:

  • 你试过在'NSDictionary *dictionary = [jsonParser objectWithString:responseString error:&error];'处设置断点吗并检查字典指向什么?

标签: iphone objective-c json nsarray nsdictionary


【解决方案1】:

您应该使用isKindOfClass: 而不是isMemberOfClass:,因为集合通常在 Cocoa 中实现为类集群。

另外,NSLog(@"%@", NSStringFromClass([[dictionary objectForKey:@"users"] class])) 比单独检查每个可能的类要短得多。

【讨论】:

  • 或者你会注意到[ ]'s 告诉你它是一个数组。
  • 当然,但这不是重点。它还很大程度上取决于 JSON 解析器的具体实现如何精确地表示一个数组——它可以是不可变的或可变的、自定义子类等。
  • 如果它是可变的或不可变的,它在 Objective-C 中仍然被表示为 NSArray 会有什么不同?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-25
  • 2012-02-05
  • 1970-01-01
相关资源
最近更新 更多