NSDictionary是零

时间:2015-04-20 08:03:09

标签: ios objective-c json nsdictionary

我想解析一个本地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

1 个答案:

答案 0 :(得分: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将为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."
    );
}