【问题标题】:How to test if Json response includes error or proper json如何测试 Json 响应是否包含错误或正确的 json
【发布时间】:2017-09-21 14:01:33
【问题描述】:

说明:在整个应用程序中,我们使用位于 AppDelegate.m 中的 Web 请求方法从服务器获取数据。我在所有这些请求中都使用了一个令牌。有时来自服务器的响应是 json:{error = "token_not_provided"} 或 {error = "token_expired"}。我需要一种方法来测试 json 是否包含这些错误或正确的 json 数据。如果发回的数据是这些错误之一,我们需要返回登录屏幕以在登录时获取新令牌。目前,我无法在请求方法中检测到这些错误,因此如果它们发生,应用程序将永远崩溃,因为无法让您重新登录。下面是 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


                           }


    }];

}

【问题讨论】:

  • if([[data valueForKey:@"error"] isEqualToString:@"token_not_provided"] || [[data valueForKey:@"error"] isEqualToString:@"token_expired"]) { 我可以'不要使用它来测试,因为如果它包含正确的 json 会崩溃 }
  • 不要在评论中添加额外信息。 Edit您的问题以及所有相关详细信息。
  • 您可以将NSURLResponse 转换为NSHTTPURLResponse 并检查http 状态码。令牌错误大多是401

标签: ios objective-c json


【解决方案1】:

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

检查错误消息是危险的,如果消息更改,您的应用将崩溃。如果您仍然想这样做,您需要检查键“错误”是否存在以及它包含的内容。

// 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 而不是数据。

【讨论】:

    猜你喜欢
    • 2021-04-08
    • 2021-06-25
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    • 2013-11-26
    • 2018-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多