NSJSONSerialization返回EXC_BAD_ACCESS

时间:2013-09-10 14:28:22

标签: objective-c json exc-bad-access nsjsonserialization

我正在使用NSJSONSerialization解析由PHP脚本创建的JSON文件。 当我清除代码(产品 - 清除)时,它完美地工作。但是当我停止程序并在没有Product - clear的情况下重新构建它时,它会在EXC_BAD_ACCESS的这一行崩溃。 我使用ARC。

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:adresse]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSError *jsonParsingError = nil;
if (response == nil) {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Connection" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alert show];
}
else {
    if (![NSJSONSerialization JSONObjectWithData:response options:0 error:&jsonParsingError]) {
        UIAlertView *jsonAlert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"JSON Parsingerror" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [jsonAlert show];
    }
    else {
        jsonData = [NSJSONSerialization JSONObjectWithData:response options:0 error:&jsonParsingError];    

通过添加此

来解决由转义的unicode字符引起的问题
NSString *escaped = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSString *name = [NSString
                   stringWithCString:[escaped cStringUsingEncoding:NSUTF8StringEncoding]
                   encoding:NSNonLossyASCIIStringEncoding];
NSData *responseData = [name dataUsingEncoding:NSUTF8StringEncoding];
responseData = [responseData subdataWithRange:NSMakeRange(0, [responseData length]-1)];   

并改变

jsonData = [NSJSONSerialization JSONObjectWithData:response options:0 error:&jsonParsingError];    

jsonData = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&jsonParsingError];    

导致SIGABRT崩溃。

我做错了什么?尽管使用了ARC,它仍然可以在产品清除之后首次运行,但随后会因EXC_BAD_ACCESS而崩溃。

我的JSON看起来像那样

[{"line":"ABC","date":"2013-10-02","description":"H\u00e4hnchenbrust mit Calvadosso\u00dfe (1,2,4,8)","art":"type1"},{"line":"DEF","date":"2013-10-02","description":"Frika‌​dellen \u0084Polpette\u0093 (Rind) mit Sardellen und Tomaten (8)","art":"type1"},{"line":"ABC","date":"2013-10-03","description":"Salatteller mit Gem\u00fcseschnitzel (4,2,8)","art":"type2"},{"line":"ABC","date":"2013-10-27","description":"Nudel-H‌​ackfleisch-Pfanne (Rind) mit Schafsk\u00e4se (2,4)","art":"type1"}]

2 个答案:

答案 0 :(得分:0)

如果要替换这些转义序列,可以使用CFStringTransform

NSMutableString *escaped = [[NSMutableString alloc] initWithData:response encoding:NSUTF8StringEncoding];
CFStringTransform((__bridge CFMutableStringRef)escaped, NULL, CFSTR("Any-Hex/Java"), YES);
NSData *unescapedData = [escaped dataUsingEncoding:NSUTF8StringEncoding];

答案 1 :(得分:0)

我想我解决了这个问题。我使用了一个单独的类JSONParser.h /.m,它一次又一次地构建。我现在只是直接使用来自父类的代码进行解析,它正在工作。