NSDictionary 突然变成一个 NSArray

NSDictionary suddenly becomes an NSArray

我有这个 URL 那 returns JSON。我将 JSON 写入字典如下:

NSData* Data = [NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:&error];
NSDictionary *schools = [NSJSONSerialization JSONObjectWithData:Data options:kNilOptions error:nil];

然后,我将该词典写入文件:

NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"schools.plist"];    
[schools writeToFile:filePath atomically:YES];

虽然 运行 代码,但我检查了似乎包含有效对象的字典:

但是,当我检查磁盘上的文件时,它看起来像一个数组:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
    <dict>
        <key>Id</key>
        <string>ffefe0f7-23bf-471f-8e99-58ada0229921</string>
        <key>Name</key>

这是预期的行为吗?我代码中的其他方法依赖于从该文件中获取字典。

仅仅因为您将变量声明为 NSDictionary 类型并不意味着对 JSONObjectWithData 的调用 确实 返回 NSDictionary.

我的猜测是您从服务器获取的文件实际上是一个包含字典的数组。在将其保存到文件之前尝试记录 JSONObjectWithData 返回的对象类型:

NSDictionary *schools = [NSJSONSerialization JSONObjectWithData:Data 
  options:kNilOptions error:nil];
NSLog(@"schools class = %@", [schools class]);