NSJSONSerialization results in EXC_BAD_ACCESS

荒凉一梦 提交于 2019-11-28 09:22:15
user1071136

It looks like a bug/shortcoming with NSJSONSerialization. The problem is caused by the escaped unicode characters (freie_pl\u00e4tze instead of freie_plätze). You have two options -

  1. Convert the escaped Unicode to real Unicode characters. Try this SO answer
  2. Use another JSON engine, such as JSONKit. JSONKit also claims to be more performant than NSJSONSerialization.

I know this question has been answered but I think some beginners may have the same issue as me and be brought to this question.

The EXC_BAD_ACCESS message was caused by malformed JSON. As I had accidentally used the same name for an Object which causes issues when converting the JSON into a dictionary.

Annoyingly it didn't bring up a formatting error. Here is an example of the JSON that caused the issue:

"levels" : {
    "level1": {
        ....
    },
    "level1": {
        ... << All objects should have different names. This should be called level2.
    },
    "level3": {
        ...
    }

To fix the issue I had to ensure that all objects of the same level had different names.

Just tested NSJSONSerialization today. With iOS 7.1. It is working. No issue found. Looks like Apple fixed the issue.

NSString* jsonString = @"{ \"freie_pl\\u00e4tze\":null}";

NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

NSError *error = nil;
NSDictionary* jsonSerializationResult = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:&error];

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