ios - 如何测试 Json 响应是否包含错误或正确的 json

标签 ios objective-c json

说明:在整个应用程序中,我们使用位于 AppDelegate.m 中的 Web 请求方法从服务器获取数据。我在所有这些请求中都使用了 token 。有时服务器的响应是 json:{error = "token_not_provided"} 或 {error = "token_expired"}。我需要一种方法来测试 json 是否包含这些错误或正确的 json 数据。如果发回的数据是这些错误中的任何一个,我们需要返回登录屏幕以在登录时获取新的 token 。现在,我无法在请求方法中检测到这些错误,所以如果它们发生,应用程序将永远崩溃,因为没有办法让您返回登录。下面是 App Delegate 中的请求方法:

-(void)makeRequest:(NSString*)urlString method:(NSString*)method params:(NSMutableDictionary*)params onComplete:(RequestBlock)callback {

// create the url
    NSURL * url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", BASE_URL, urlString]];
    NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:url];


    KeychainItemWrapper *keychainItem = [[KeychainItemWrapper alloc] initWithIdentifier:@"YourAppLogin" accessGroup:nil];

    NSString *token = [keychainItem objectForKey:(__bridge id)(kSecAttrAccount)];

    if(!token){

        token = @"NO_TOKEN";



    }


    // set the method (GET/POST/PUT/UPDATE/DELETE)
    [request setHTTPMethod:method];
    [request addValue:[@"Bearer " stringByAppendingString:token] forHTTPHeaderField:@"Authorization"];


// if we have params pull out the key/value and add to header
    if(params != nil) {
         NSMutableString * body = [[NSMutableString alloc] init];
        for (NSString * key in params.allKeys) {
            NSString * value = [params objectForKey:key];
            [body appendFormat:@"%@=%@&", key, value];
    }
        [request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
}

// submit the request
    [NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, 
NSData *data, NSError *connectionError) {

                           // do we have data?
                           if(data && data.length > 0) {

                               NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

                               // if we have a block lets pass it
                               if(callback) {
                                   callback(json);


                             }

                               HERE IS WHERE I WANT TO TEST IF WE HAVE ERROR JSON or PROPER JSON


                           }


    }];

最佳答案

如果您可以修改服务器上的接口(interface),您可以发送一个 bool 值来确定请求是否成功。诸如“成功”之类的东西 = 1 或 0。

检查错误消息是危险的,如果消息发生变化,您的应用程序将崩溃。如果你想这样做,你需要检查键“error”是否存在,然后检查它包含什么。

// Check if key is available.
if ([json.keys containsObject:@"error"]) {
    if ([json[@"error"] isEqualToString:@"token_not_privided"] || [json[@"error"] isEqualToString:@"token_expired"]) {
        // Token is invalid
    } else {
        // Something different went wrong.
    }
}
// Nothing is wrong, lets inform the caller. 
else {
    if (callback) {
        callback(json);
    }
}

您应该检查 json 而不是数据。

关于ios - 如何测试 Json 响应是否包含错误或正确的 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46346020/

相关文章:

objective-c - 如何在鼠标悬停时突出显示 IKImageBrowserView 的单元格?

javascript - AngularJS 更新 JSON 文件

iphone - dropbox如何在后台同步照片并获得苹果的认可?

ios - 无法在一个文件中使用另一个文件中的函数

ios - X代码 4.5/iOS6 : orientation issue with my iPad app in Landscape mode

objective-c - 单个对象上的removeObject 与removeObjectAtIndex 之间有性能差异吗?

iphone - iOS 中涉及屏幕抓取的 Objective-C 和 Cocoa Touch 问题

javascript - 如何使用ajax和Stringify在java中解码json输入

javascript - 按列表中的编号/顺序查找 json 对象中的元素

iOS 如何执行多个 NSInputStream