2015-04-20 34 views
4

我想解析一個本地JSON,我試圖這樣做,但是testDict是零。任何人都可以幫助我嗎?NSDictionary是零

- (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 *[email protected]"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

+0

你可以發佈你嘗試分析請 –

+6

又是什麼'err'告訴你的JSON? – Wain

+1

檢查錯誤! –

回答

1

我用下面的代碼:

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文件開頭添加{,最後加上}。 您可以通過檢查this site來查看您的JSON格式是否正確。如果您的數據無效,您的NSDIctionary將爲空。

把你的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." 
    ); 
}