繁体   English   中英

在iOS应用中解析JSON对象

[英]Parse JSON object in iOS app

嗨,我在我的项目中对Ios非常陌生,我正在集成Web服务,很好。

在这里,当我向服务器发送正确的请求时,响应来自服务器,例如“我的第一个响应”下面。

而且,如果我们向服务器发送了错误的请求,则响应来自服务器,例如“我的第二个响应”下方。

因此,我们不知道发送请求后从服务器获得哪种类型的Json对象。

在这里,我的主要要求是,如果我们从服务器获得正确的响应(如下面的第一个响应),那么我们可以保存所需的所有元素。

而且,如果我们收到错误的响应(如第二个响应下方),那么我们将如何查找以及如何打印该消息,因为有时我们会收到正确的响应,而有时我们会收到来自服务器的错误响应,因此我们如何查找并保存该消息响应。

请帮我。

如果发送适当的请求,则响应:-

responseObject = {

           {
            Name = Broad;
            DeptNo = A00;
            BatchNo = 23;
            DeptId = 120;
          },

          {
            Name = James;
            DeptNo = B00;
            BatchNo = 23;
            DeptId = 123;
          },
     }

如果我们发送了错误的请求,那么响应:-

responseObject = {

    error = 1;
    message = "Invalid Code";
}

我的代码:

- (void)viewDidLoad {
    [super viewDidLoad];

    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                              @"12345678"  ,@"scacode",
                              nil];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"my url"]
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:15.0];

    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPMethod:@"POST"];

    NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        });

        if (error) {

            NSLog(@"dataTaskWithRequest error: %@", error);
        }

        if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
            NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
            if (statusCode != 200) {                

                NSLog(@"Expected responseCode == 200; received %ld", (long)statusCode);
            }
        }

         NSError *parseError;
         id responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];

         if (!responseObject) {

             NSLog(@"JSON parse error: %@", parseError);

         } else {

             NSLog(@"responseObject = %@", responseObject);
         }
    }];
    [task resume];
}

您可以按照以下方式使用:

NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];

if([responseObject objectForKey:@"error"] == nil)
{
   //You are getting correct response
}
else{
   // You are getting response with error
}

您可以检查响应是否包含错误的密钥。 否则,您可以在服务器端将new变量用于所有响应,例如statusCode。 因此,如果遇到错误或成功,则可以将服务器端设置为statusCode。 这是非常清晰的方法。

您可以使用UIAlertView显示错误消息

if([responseObject objectForKey:@"error"] == nil)
{
   //You are getting correct response

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"Your Message" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
   [alert show];
}
else
{
   // You are getting response with error
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"Error Message" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
   [alert show];
}

我猜你还没有发布整个responseObject(发送适当的请求时)。 假设响应正确时,您将得到error = 0键,则可以执行以下操作:

NSMutableDictionary *jsonDictionary= [NSMutableDictionary alloc]init]

jsonDictionary=responseObject;

if([jsonDictionary valueForKey:@"error"]==@"0"]
{
//do some stuff
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Invalid Request" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[alert show];
}

暂无
暂无

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

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