Parsing JSON with NSJSONSerialization: Error 3840 - Data Corrupted?

匆匆过客 提交于 2019-12-06 02:36:06

OK, as always, checking the actual data instead of the string representation pays - thanks @Bavarious.

It turns out that the PHP script(s) in charge of creating the JSON were all "UTF8 with BOM", so PHP returned a BOM for every script involved.

Once I changed all the PHP files to "UTF8 without BOM" everything seems to be fine - need to test this on the MAC though.

Sorry to interrupt, keep up the good work.

(@Bavarious: If you'd like to write an answer, I'd be happy to upvote and accept it, as you pointed me to the solution).


Was able to parse the JSON now as expected. Making a mental note to always double-check the text file encoding.

    NSURL *theURL = [NSURL URLWithString:@"http://yourdataurl"];

    NSMutableURLRequest *storeRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];

    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [NSURLConnection sendAsynchronousRequest:storeRequest queue:queue
                       completionHandler:^(NSURLResponse *response,     NSData *data, NSError *connectionError) {
                               if (!connectionError) {
                                   NSError *error;

                                   NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

                                   NSData *theData = [dataStr dataUsingEncoding:NSUTF8StringEncoding];

                                   NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:theData options:0 error:&error];


                                   if (!jsonResponse || error)
                                   {
                                       NSLog(@"Error");
                                   }
                                   else
                                   {
                                       // Everything is ok..
                                   }
                               }
                           }];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!