NSDictionary is nil



我想解析一个本地 json,我试图这样做,但testDict为零。 谁能帮我?

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
    [self.searchResult removeAllObjects];
        NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@", searchText];
    NSString * firstLetter = [searchText substringWithRange:[searchText rangeOfComposedCharacterSequenceAtIndex:0]];
    NSError *err = nil;
    NSString *aux=@"english_";
    NSString *updated = [aux stringByAppendingString:firstLetter];
    NSString *dataPath = [[NSBundle mainBundle] pathForResource:updated ofType:@"json"];
    testDict = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath] options:kNilOptions error:&err];

Json看起来像这样:

"Caaba": "(n.) The small and nearly cubical stone building, toward which all Mohammedans must pray.",
   "Caas": "(n. sing. & pl.) Case.",
   "Cab": [
      "(n.) A kind of close carriage with two or four wheels, usually a public vehicle.",
      "(n.) The covered part of a locomotive, in which the engineer has his station.",
      "(n.) A Hebrew dry measure, containing a little over two (2.37) pints."
   ],

我正在检查是否是验证 json

我使用了以下代码:

NSString *path = @"/Users/JohnApple/Desktop/myJsonFileForThisTest.json";
NSError *err;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:path] options:kNilOptions error:&err];
NSLog(@"Here is the NSDicitonary if this worked --> %@",dict);
NSLog(@"Here is the NSError if it failed --> %@", err);

当我使用您上面提供的 Json 数据时:

"Caaba": "(n.) The small and nearly cubical stone building, toward which all Mohammedans must pray.",
"Caas": "(n. sing. & pl.) Case.",
"Cab": [
  "(n.) A kind of close carriage with two or four wheels, usually a public vehicle.",
  "(n.) The covered part of a locomotive, in which the engineer has his station.",
  "(n.) A Hebrew dry measure, containing a little over two (2.37) pints."
],

我收到此错误:

The data couldn’t be read because it isn’t in the correct format." (JSON text did not start with array or object and option to allow fragments not set

事实证明,您的 JSON 格式不正确。要修复您的 Json,请在文件中 json 的开头添加一个{,并在最后添加一个}。您可以通过检查此站点来检查您的 JSON 格式是否正确。如果数据无效,则 NSDItionary 将为 null。

将 Json 放入正确的格式后,将正确显示以下数据:

{
    Caaba = "(n.) The small and nearly cubical stone building, toward which all Mohammedans must pray.";
    Caas = "(n. sing. & pl.) Case.";
    Cab =     (
        "(n.) A kind of close carriage with two or four wheels, usually a public vehicle.",
        "(n.) The covered part of a locomotive, in which the engineer has his station.",
        "(n.) A Hebrew dry measure, containing a little over two (2.37) pints."
    );
}

最新更新