2016-01-13 68 views
0

我有這個URL返回JSON。我寫的JSON的解釋如下:NSDictionary突然變成NSArray

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]; 

運行代碼時,我檢查字典,似乎包含有效對象:

enter image description here

然而,當我檢查磁盤上的文件,它看起來像一個數組:

<?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> 

這是預期的行爲嗎?我的代碼中的其他方法依賴於從該文件中獲取字典。

+1

'的NSLog(@ 「類:%@」,[NSJSONSerialization JSONObjectWithData:數據選項:kNilOptions錯誤:零]類] )'真的返回一個NSDictionary?難道你的JSON實際上返回一個NSArray?另外,請檢查「學校」是否被「覆蓋」(重置)在某處 – Larme

+0

它看起來像'JSONObjectWithData'返回包含'NSDictionary's的'NSArray's。 – keithbhunter

+0

看我添加的插圖。當「學校」啓動時,似乎沒有json數據 – Sjakelien

回答

1

僅僅因爲你聲明你的變量是NSDictionary類型並不意味着調用JSONObjectWithData真的返回一個NSDictionary

我的猜測是,你從服務器獲得的文件實際上是一個包含字典的數組。嘗試登錄由JSONObjectWithData返回的對象的類型,你將它保存到一個文件之前:

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

schools class = __NSCFArray的問題。確實。有沒有簡單的方法把它變成字典? – Sjakelien

+0

@Sjakelien你爲什麼想這樣做? – trojanfoe

+0

我在數據中看到的是一個包含單個元素和字典的數組。只需獲取第一個元素即可。這應該是你需要的字典。 –