【问题标题】:Exception not handled in JSONObjectWithData iOS?JSONObjectWithData iOS 中未处理异常?
【发布时间】:2019-01-15 09:35:36
【问题描述】:

我在将NSData 解析为字典时发生随机崩溃。我使用了以下代码。

 -(NSArray *)enumDataParser:(NSMutableData *)responseData
    {   
        @try { 
            NSError *error;      
            NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
        }
        @catch (NSException *exception) {
            [[IFieldServiceCrashLog sharedLog] writeExceptionLogFile:exception];
            [self performCatchOperation:exception];
        }
    }

有时我得到“nil”,有时我的应用程序崩溃 (Exception not catched)。

我确定responseData 不为零,因为无论何时发生崩溃,"error" 都不会给我一个原因(发现错误为零)。

应用程序在方法JSONObjectWithData 本身崩溃。我该如何解决这个问题或处理异常?

【问题讨论】:

  • 好像和“Swift”无关,是不是需要加标签?
  • 如果我没记错的话,如果responseData 为 nil,您无法捕获所有错误,并且您无法捕获错误。可能还有其他您无法捕捉到的错误。只需检查 responseData 是否为零。
  • 没有必要将它包含在@try @catch 中,因为在Objective-C 中这个方法不会抛出异常,或者至少不会因为序列化错误。
  • @Larme。 responseData 不为零。当我将消息 JSONObjectWithData 发送到响应数据时,它会崩溃。任何解决方法?
  • 如何获得responseData?您的回复是返回NSData,还是返回NSString,您使用dataUsingEncoding 转向NSData

标签: ios objective-c json exception


【解决方案1】:

JSON 仅反序列化 Dictionary 或 Array,所以可以查看日志。 其他,请参见选项类型:-> 枚举 NSJSONReadingOptions like "options:NSJSONReadingAllowFragments"

typedef enum NSJSONReadingOptions : NSUInteger {
    NSJSONReadingMutableContainers = (1UL << 0),
    NSJSONReadingMutableLeaves = (1UL << 1),
    NSJSONReadingAllowFragments = (1UL << 2)
} NSJSONReadingOptions;

例子:

NSError *error = nil;

id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error];

if (error != nil) {
    NSLog(@"***** %@", error.localizedDescription);
} else if (jsonObject != nil) {
    NSLog(@"*** JSON Data converted to NSObject!");
    if ([jsonObject isKindOfClass:[NSDictionary class]]) {
        NSDictionary *deserializedDictionary = (NSDictionary *)jsonObject;
        NSLog(@"JSON Obj class: %@", NSStringFromClass([deserializedDictionary class]));
        NSLog(@"*** its Dictionary Object from JSON Data: %@", deserializedDictionary.description);
    } else if ([jsonObject isKindOfClass:[NSArray class]]) {
        NSArray *deserializedArray = (NSArray *)jsonObject;
        NSLog(@"JSON Obj class: %@", NSStringFromClass([deserializedArray class]));
        NSLog(@"*** its Array Object from JSON Data: %@", deserializedArray.description);
    } else {
        NSLog(@"JSON Obj class: %@", NSStringFromClass([jsonObject class]));
        NSLog(@"*** its UNKNOWN Object from JSON Data: %@", jsonObject);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-27
    • 1970-01-01
    • 2011-11-19
    • 1970-01-01
    • 1970-01-01
    • 2011-11-02
    • 1970-01-01
    相关资源
    最近更新 更多