【问题标题】:How to read json in iOS using sbjson如何使用 sbjson 在 iOS 中读取 json
【发布时间】:2014-01-01 18:54:31
【问题描述】:

我正在尝试读取以下 json:

[{"result":"1","msg":"Login Successful.”,”title":"Login","redirect":"index.php","servers":"{\"140\":\"10 minute Email\"}","server”:”xxx.xxx.xxx.xxx”}]

像这样:

 NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
                NSLog(@"Response ==> %@", responseData);
                
                SBJsonParser *jsonParser = [SBJsonParser new];
                NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
                NSLog(@"%@",jsonData);
                NSInteger success = [(NSNumber *) [jsonData objectForKey:@"result"] integerValue];
                NSLog(@"%d",success);
                if(success == 1)
                {
                    NSLog(@"Login SUCCESS");
                    [self alertStatus:@"Logged in Successfully." :@"Login Success!"];
                    
                } else {
                    
                    NSString *error_msg = (NSString *) [jsonData objectForKey:@"error_message"];
                    [self alertStatus:error_msg :@"Login Failed!"];
                }

但我收到以下错误:

2014-01-01 20:44:08.857 服务器监视器[9704:70b] -[__NSArrayM objectForKey:]: 无法识别的选择器发送到实例 0x8e59950

2014-01-01 20:44:08.857 服务器监视器[9704:70b] 例外: -[__NSArrayM objectForKey:]:无法识别的选择器发送到实例 0x8e59950

我认为问题在于 json 是一个数组,我该如何处理呢?

【问题讨论】:

标签: ios objective-c json sbjson


【解决方案1】:

问题是你的 JSON 的根对象是一个数组:

[ … ]

但你错误地认为它是一本字典:

NSDictionary *jsonData = (NSDictionary *)[jsonParser objectWithString:responseData error:nil];

如果响应始终是一个包含一个对象的数组,您可以这样做:

NSArray *jsonArray = (NSArray *)[jsonParser objectWithString:responseData error:nil];
NSDictionary *jsonData = [jsonArray lastObject];

但更安全的方法是检查类:

NSObject *object = [jsonParser objectWithString:responseData error:nil];
if ([object isKindOfClass:[NSArray class]]) {
    // it's an array …
} else if ([object isKindOfClass:[NSDictionary class]]) {
    // it's a dictionary …
}

最后,

  • 您可能应该使用 NSJSONSerialization 而不是 SBJSON。
  • 您不应将nil 传递给错误参数;您应该添加错误处理。

【讨论】:

    【解决方案2】:

    这样使用

    NSString *theJSON = [request responseString];
    
     // Now we have successfully captured the JSON ouptut of our request.
    
    // Alloc and initialize our JSON parser.
    
     SBJsonParser *parser = [[SBJsonParser alloc] init];
    
     // Actually parsing the JSON.
    
     NSMutableDictionary *jsonDictionary = [parser objectWithString:theJSON error:nil];
    

    愉快的编码

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多